Get random json object - javascript

I want to get random hotelCode (for example CUNMXSAKU but randomly) object.
Is it possible to have this object randomly in javaScript or Jquery.
My JSON:
var simulatedHotelCodes = {
"CUNMXSAKU" : {
"roomCodes" : "DEAL, JRST, JPOV, JSSW, PJRS, PJOV, PJSW, RMOV, RMOF, PRES"
},
"CUNMXMAYA" : {
"roomCodes" : "ROAI, FVAI, DXAI, CAAI, SUAI, CABA, SIGA, PRAI, POFA, ROOM, FMVW, DELX, CASA, SUIT, CASI, SIGN, PROF, PROFS"
},
"CUNMXDPAV" : {
"roomCodes" : "GDVW, MRNA, FMLY, DFAM, HNDO, OCVW, DOLP, FMOV, PCDO, HNOC, PCOV, PFOV, ROHO"
},
"CUNMXHIDD" : {
"roomCodes" : "JRST, JRSU, DOME"
},
"CUNMXDSAN" : {
"roomCodes" : "DEAL, DELX, DEXBA, DXOF, DOFB, PROV, PROF, PROB, POFC, HONY, FAMI, PRJS, DEBL, PRDD"
}
};
Output:
"CUNMXMAYA" : {
"roomCodes" : "ROAI, FVAI, DXAI, CAAI, SUAI, CABA, SIGA, PRAI, POFA, ROOM, FMVW, DELX, CASA, SUIT, CASI, SIGN, PROF, PROFS"
}
or
"CUNMXHIDD" : {
"roomCodes" : "JRST, JRSU, DOME"
}
Randomly
Thanks in advance

I'd use Object.getOwnPropertyNames() to get an array of all the properties, then pick a random index.
var simulatedHotelCodes = {
"CUNMXSAKU" : {
"roomCodes" : "DEAL, JRST, JPOV, JSSW, PJRS, PJOV, PJSW, RMOV, RMOF, PRES"
},
"CUNMXMAYA" : {
"roomCodes" : "ROAI, FVAI, DXAI, CAAI, SUAI, CABA, SIGA, PRAI, POFA, ROOM, FMVW, DELX, CASA, SUIT, CASI, SIGN, PROF, PROFS"
},
"CUNMXDPAV" : {
"roomCodes" : "GDVW, MRNA, FMLY, DFAM, HNDO, OCVW, DOLP, FMOV, PCDO, HNOC, PCOV, PFOV, ROHO"
},
"CUNMXHIDD" : {
"roomCodes" : "JRST, JRSU, DOME"
},
"CUNMXDSAN" : {
"roomCodes" : "DEAL, DELX, DEXBA, DXOF, DOFB, PROV, PROF, PROB, POFC, HONY, FAMI, PRJS, DEBL, PRDD"
}
};
var properties = Object.getOwnPropertyNames(simulatedHotelCodes);
var index = Math.floor(Math.random() * properties.length);
var output = {};
output[properties[index]] = simulatedHotelCodes[properties[index]];
console.log(output);

If you only care about modern browsers, check #dave's answer which is cleaner (and it probably has a better performance). If you want a cross-browser solution here there is an option:
// Define amount of json objects
var length = 0;
for (var key in json)
length++;
// Get random index and iterate until get it
var rnd = Math.floor(Math.random()*length),
i = 0,
obj;
for (var key in json) {
if (i == rnd) {
obj = {};
obj[key] = json[key];
break;
}
i++;
}
// obj has the random item
Note that you would need the random selected key to use obj. You could change this:
obj = {};
obj[key] = json[key];
to this:
obj = json[key];
to save only the random item value.
http://jsfiddle.net/paska/m2y7gvnp/1/

Yes it is possible. But it would be more easy if you put those object in array so that you can access those object through array index. As array index is an integer, you can randomly generate that array index and then access that object.

Related

How to find and update key data?

I have a document like this in mongo collection :
{
"_id" :"sdsfsfd323323323ssd",
"data" : {
"('State', 'Get-Alert', 'BLIST_1', 'MessageData')" : [
"$B_Add-Server",
"$B_Pool1_0_Server"
],
"('State', \"Get-Server -Server 'uds412'\"):[
"$B_Add-Server",
"$B_Pool2_0_Server"
]
}
and I need to update "uds412" to "newValue".
Someone please help , how to find and replace it ?
Thanks
You can convert you valid JSON object into string and replace string to new value and again parse it into valid JSON object.
obj={ ...YOUR JSON OBJECT... }
newobj = JSON.parse(JSON.stringify(obj).replace('uds412','newValue'))
Finally , i solve it like this,
problem was , i need to find substring from key and update that key.
// first query the document
db.server_col.find().forEach(function (docs) {
var tempData = {};
var tempDataAr = [];
for (var key in docs["data"]) {
var find = /'uds412'/;
if (key.match(find)) {
tempDataAr = docs["data"][key]
key = key.replace('uds412', 'newValue');
tempData[key] = tempDataAr;
} else {
tempData[key] = docs["data"][key];
}
}
print(tempData);
// then you can update it
db.server_col.update({ "_id" : ObjectId("sdfsfdafs")}, { $set: { 'data':tempData } }, { multi: true })
});

How can I get object by key? [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 7 years ago.
var test = [
{
id : 'user01',
pos0 : 2
},
{
id : 'user01',
pos0 : 3
},
{
id : 'user02',
pos1 : 5
},
{
id : 'user02',
pos1 : 6
},
{
id : 'user03',
pos2 : 8
},
{
id : 'user03',
pos2 : 9
}
]
This is example data,
and
I want if I passed 'pos2', get test[4] and test[5].
//like this :
function getObjectByKey(array, key){
// dosomething
};
..
var testArray = getObjectByKet(test, 'pos2');
I tried to use $.inArray or $.map, but how to use them.
How can i do this?
Regards.
Please try this,
function getObjectByKey(array, key){
var users=[];
$.map(array, function (user, index) {
if (user[key])
users.push(user)
});
return users;
};
hope this will help you.
Also change your function calling. You miss spelled the function name
Try this while calling the method
var testArray = getObjectByKey(test, 'pos2');
I would suggest to use Array.prototype.map() method to iterate an array. Like this:
var test = [
{
id : 'user01',
pos0 : 2
},
{
id : 'user01',
pos0 : 3
},
{
id : 'user02',
pos1 : 5
},
{
id : 'user02',
pos1 : 6
},
{
id : 'user03',
pos2 : 8
},
{
id : 'user03',
pos2 : 9
}
]
var user;
test.map(function(v) { if(v.id == 'user03') user = v; });
Here is a FIDDLE.

mongodb mapreduce script to count total orders fails

I'm new to mongodb and I'm planning to migrate from SQL to noSQL. I've a lot of stored procs and I think mapReduce is the "equivalent" in noSQL world.
I've started with a js script that tries to count orders by customer, but it gives wrong result.
The script is:
db = connect("localhost:27017/pgi");
for(i=0;i<1000;i++){
db.orders.insert(
{
"cust_id" : 1,
"total" : 100,
});
}
for(i=0;i<1000;i++){
db.orders.insert(
{
"cust_id" : 2,
"total" : 100,
});
}
var res = db.orders.find({cust_id : 1});
print("Total Orders for customer 1:" + res.count());
var res = db.orders.find({cust_id : 2});
print("Total Orders for customer 2:" + res.count());
//map reduce
var map = function(){
emit(this.cust_id, 1);
}
var reduce = function(key, values){
var c = 0;
for (index in values) {
c += 1;
}
return {cust_id : key, count: c};
}
var res = db.orders.mapReduce(
map,
reduce,
{
out : {inline : 1}
}
);
res.find({}).forEach(function(item){
printjson(item);
});
the expected output is 1000 for each customer but I'm getting this:
connecting to: test
connecting to: localhost:27017/pgi
Total Orders for customer 1:1000
Total Orders for customer 2:1000
{ "_id" : 1, "value" : { "cust_id" : 1, "count" : 101 } }
{ "_id" : 2, "value" : { "cust_id" : 2, "count" : 101 } }
Could someone kindly tell me what was wrong.
Regards,
Using MapReduce it's essential that the reducer output is of the same format as the mapper output value as the reducer may run multiple times for the same key. Also, the reducer does not need to output the key, only the resulting value after performing whatever operations are required on the input array.
So in your case the mapper looks correct for counting orders by customer, but the reducer should just output the total count rather than generating an Object with the key and count.
Also the reducer needs to sum the value of each index, not increment by 1, to handle the case where it is operating on the output of previous invocations of the reduce function.
var reduce = function(key, values){
var c = 0;
for (var index in values) {
c += values[index];
}
return c;
}

Issue Pushing values in to objects Javascript

Have some issue with push the values in to the javascript array object. Please any one give me the perfect solution
Class code :
var myfuns = ( function(undefined) {
var myarr ={};
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
}
}
function _getList() {
return $.extend(true, {}, myarr);
}
return {
add : _add,
getList : _getList
}
}());
Here am calling and manage the values and keys
function setmydetails(){
var my_param = {
current_info : {
pg : '#tset',
no : 12,
name : "john",
row : 0,
},
userprofile : [],
class : [],
marks : [],
games : []
};
myfuns.add(my_param);
}
Now i got the array
myfuns.getList() // GOT proper array what i passed in my_param
Question : How to modify the existing values from any one of the Inner array from the myarr Obj
Ex: Once First array created later have to modify some from "myarr.current" = > Change current_info.row to 2222
Similar i have to add some array in to " myarr.class " etc
I would like to say try this one not tested
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
$.extend( myarr.current, arrayparam);
}
}
proper source : https://api.jquery.com/jquery.extend/

Regular expression for accessing map in java script

How to I fetch some rows of particular pattern ?
var list = {
kk_list_name : "jack",
kk_list_no : "123",
kk_first_name :"Reck",
kk_first_no : "5555"
}
Here I want a map with key starting with kk_list
I tried some thing like this, which obviously didnt work.
console.log(list["kk_list_\w+"])
You can try something like this:
function filterArray( list, regex )
{
var outputArray = {};
for( var key in list )
{
if( key.match( regex ) )
{
outputArray[key] = list[key];
}
}
return outputArray;
}
var list = {
kk_list_name : "jack",
kk_list_no : "123",
kk_first_name :"Reck",
kk_first_no : "5555"
}
console.log( filterArray( list, /kk_list_\w+/ ) );
It uses a function to filter the array and make a new one with the regex-selected keys.
You can reduce the object to one with just the keys matching a specified regex using the following:
Object.prototype.reduce = function(regex) {
var newObj = {}, x;
for(x in this) if(this.hasOwnProperty(x) && (!regex || regex.test(x))) newObj[x] = this[x];
return newObj;
};
And then call it as list.reduce(/_first.*$/) => Object {kk_first_name: "Reck", kk_first_no: "5555"}
You can use the following code:
var list = {
kk_list_name : "jack",
kk_list_no : "123",
kk_first_name :"Reck",
kk_first_no : "5555"
}
var line=JSON.stringify(list);
var ar=line.match(/(kk_list[^" :]*)/g)
ar.forEach(function(val){
console.log(eval("list."+val));
});
OUTPUT
jack
123

Categories

Resources