Issue Pushing values in to objects Javascript - 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/

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 do I get items from localStorage?

In my app I've got 2 functions to work with localStorage.
When I add the first and second items, it works properly, but when it is the third item, it gives an error.
Here are the functions:
w.getLocalStorage = function() {
var c = localStorage.getItem('cities');
var arr = [];
arr.push(c);
return c ? arr : [];
}
w.setLocalStorage = function(data, googleData, cities, name) {
if (data) {
city.name = data.name;
city.coord.lat = data.coord.lat;
city.coord.lon = data.coord.lon;
cities.push(JSON.stringify(city));
// console.log(city);
localStorage.setItem("cities", cities);
} else if (googleData) {
city.name = name;
city.coord.lat = googleData.results[0].geometry.location.lat;
city.coord.lon = googleData.results[0].geometry.location.lng;
console.log('cities', cities);
cities.push(JSON.stringify(city));
// console.log(cities, city);
localStorage.setItem("cities", cities);
}
}
Here is what it returns for the first 2 items:
Array[1]
0 : "{"name":"Pushcha-Voditsa","coord":{"lat":50.45,"lon":30.5}}"
1 : "{"name":"Kyiv","coord":{"lat":50.4501,"lon":30.5234}}"
Here is what when the third items is added:
Array[1]
0 : "{"name":"Pushcha-Voditsa","coord":{"lat":50.45,"lon":30.5}}, {"name":"Kyiv","coord":{"lat":50.4501,"lon":30.5234}}"
1 : "{"name":"Kyiv","coord":{"lat":50.4501,"lon":30.5234}}"
How can I fix this?
As you can only store string in localStorage, to persist object convert them in stringified format using JSON.stringify() method and on retrieval use JSON.parse() to parses the JSON string to construct the JavaScript value or object.
Here are the code snippet, which require attention. You should persist stringified cities data
cities.push(city);
localStorage.setItem("cities", JSON.stringify(cities));
While retrieval, parse it JavaScript object
var cities = localStorage.getItem('cities');
var c = cities ? JSON.parse(cities) || [];

JS converting an array to a json linked list?

I am new to JS and the concepts of organising data elude me a little, trying to take data from a specific array format (as this is what I have to work with) and output it into another specific JSON format.
This is to pass data to the D3 sankey module
https://github.com/d3/d3-plugins/blob/master/sankey/sankey.js
I can't figure out is how to add the index of the node into the links, rather than the name.
Really I am just totally lost with it!
I made a fiddle here:
https://jsfiddle.net/adamdavi3s/kw3jtzx4/
Below is an example of the data and the output required
var data= [
{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var output= {
"nodes":[
{"name":"Agricultural 'waste'"},
{"name":"Bio-conversion"},
{"name":"Electricity grid"},
{"name":"Losses"},
{"name":"Liquid"}
],
"links":[
{"source":0,"target":1,"value":124.729},
{"source":1,"target":2,"value":0.597},
{"source":1,"target":3,"value":26.862},
{"source":1,"target":4,"value":280.322},
{"source":3,"target":4,"value":280.322}
]
};
Here is my code from the fiddle thusfar
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var sourceArray=[];
for (var i=0; i <data.length; i++ ) {
var node= {"name":data[i].source};
var found = jQuery.inArray(node, sourceArray);
if (found < 0) {
// Element was not found, add it.
sourceArray.push(node);
}
}
console.log(sourceArray);
In javascript:
[ ] annotations are used to describe an Array, like:
var names=["John","Lisa"]
{ } Its are used to describe an Object
var person = {"name" : "John", "age" : 23}
You can use them inside one another
var people=[{"name" : "John", "age" : 23},{"name" : "Lisa", "age" : 44}]
Try this:
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var sourceArray=[];
var linkArray=[];
for (var i=0; i <data.length; i++ ) {
var node= {"name":data[i].source,};
var link= {
"source":i,
"target":data[i].target,
"value":data[i].value,
};
var found = jQuery.inArray(node, sourceArray);
if (found >= 0) {
// Element was found, remove it.
sourceArray.splice(found, 1);
linkArray.splice(found, 1);
} else {
// Element was not found, add it.
sourceArray.push(node);
linkArray.push(link);
}
}
finalArray={"nodes": sourceArray,"links": linkArray}
console.log(finalArray);
https://jsfiddle.net/9x4rdyy7/
Array.reduce() is perfect for this use case ;)
Take a look.
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var output = data.reduce(function(result, item){
for(key in search = ['source','target']) {
var value = item[search[key]];
if(! result.index.hasOwnProperty(value)){
result.index[value] = Object.keys(result.index).length;
result.nodes.push({name: value});
}
}
result.links.push({
source: result.index[item.source],
target: result.index[item.target],
value: Number(item.value)
});
return result;
}, {nodes: [], links: [], index: {}});
delete output.index;
console.log(output);

how to loop inside an array that is inside an array in javascript?

I have problems while looping through an array. That is, inside an object which is inside of an array in javascript. Below is my loop and under is my object.
I want retrieve the names of the objects. please, compare my $('#searchbox').keypress function and my var animals_data object
$('#searchbox').keypress(function (e) {
if (e.which == 13) {
var search_text = $('#searchbox').val();
console.log(search_text)
var filteredData = {
animalsR: animals_data.category.animalsR.filter(function(d){
if (d.name.search(search_text) > -1){
return true;
}
return false;
})
};
var source = $("#album-template-Reptile-result").html();
var template = Handlebars.compile(source);
var html = template(filteredData);
$('#content').html(html);
}
});
var animals_data = {
category : [{
name : "Reptiles",
animalsR : [
{
image1 : "url" ,
image2 : "url" ,
name : "Snake",
description : "text"
},
{
image1 : "url",
image2 : "url",
name : "Crocodilia",
description : "text"
}
]
}]
};
You can get first element in array via [0], category in your case is an Array
animals_data.category.animalsR.filter
// ^---- your error here, it's an array
For iterating arrays you can use Array.prototype.forEach()
animals_data.category[0].animalsR.forEach(function(e){
// do something ...
})
But what if I have many objects in the array category. Each of which contains an array that I want to itterate through.
For that you can use nested Array.forEach() method, like this:
animals_data.category.forEach(function(a) {
a.animalsR.forEach(function(e) {
// do something
});
});

Get random json object

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.

Categories

Resources