I would like to cache data from remote database locally to use it in my javascript application. I do not need any excesses such as SQL requests to local data, so I decide just to store database records in array of objects in the following way:
<script type="text/javascript">
var json0 = '{"1" : {"fname": "fname1", "sname": "sname1"}, "2" : {"fname": "fname2", "sname": "sname2"}}';
var json1 = '{"2" : {"data": "11/05/2014", "time": "11:30:18", "person": "data0[1]"}, "6" : {"data": "24/06/2014", "time": "16:11:05", "person": "data0[2]"}, "8" : {"data": "11/10/2014", "time": "12:15:27", "person": "data0[1]"}}';
var data0 = JSON.parse(json0);
var data1 = JSON.parse(json1, function (k, v) {
try {
return eval(v);
} catch (e) {
return v;
}
});
console.log(data1);
</script>
The question is about the memory usage. If the objects in array data1 will store the reference to the objects from data0 in the property "person" or they will store the copy of these objects?
as reducing version of your example shows, data0 will be stored by reference.
var tt = {f1: 'aa', f2: 'bb'}
var rr = eval('tt');
console.log(rr.f1); // 'aa'
rr.f1 = 'cc';
console.log(tt.f1); // 'cc'
But using eval(..) is bad way: Why is using the JavaScript eval function a bad idea? . Use local storage instead as jeff said.
Related
I have an array
[
{"field" : "flight1", "value" : "123"},
{"field" : "flight2", "value" : "456"}
]
is it possible to become key value pair?
{
"flight1" : "123",
"flight2" : "456"
}
You can use reduce() and return object as result.
var arr = [{"field" : "flight1", "value" : "123"},{"field" : "flight2", "value" : "456"}]
var result = arr.reduce(function(r, e) {
r[e.field] = e.value;
return r;
}, {});
console.log(result)
The new Map() constructor can do this for you:
var data = [
{"field": "flight1", "value": "123"},
{"field": "flight2", "value": "456"}
];
var result = new Map(data.map(obj => [obj.field, obj.value]));
If you're not familiar with Map objects, they work almost exactly the same as plain objects, except they are a little easier to iterate over, and have a .size property.
But if you prefer to have a plain object, you can get one this way:
var result = Object.fromEntries(data.map(obj => [obj.field, obj.value]));
You could map the key value pair and assign it to an object.
var data = [{ field: "flight1", value: "123" }, { field: "flight2", value: "456" }],
result = Object.assign(...data.map(a => ({ [a.field]: a.value })));
console.log(result);
you could use a standard for loop:-
var data = [{"field" : "flight1", "value" : "123"},{"field" : "flight2", "value" : "456"}];
var obj = {};
for (var i = 0; i < data.length; i++)
obj[data[i].field] = data[i].value;
console.log(obj);
This might help someone another day. I tried all the examples above, but each time the console was giving me something like this:
{
flight1: "123",
flight2: "456"
}
My problem was that I was converting a serialized array way to soon which resulted in lots of tiny problems. Below was the code that didn't work:
var data = $('#myform').serializeArray();
data = JSON.stringify(data);
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value })));
database.addUser(result);
Note that flight1 and flight2 lost their double quotes. Below was my solution:
var data = $('#myform').serializeArray();
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value }))); //result was already turned into a JSON array
database.addUser(result);
NB: This was a code for submitting user information to a database (neDB) using the electron framework
When I make an API request, the API server returns me a JSON object. How do I parse the JSON object to their designated types in Javascript?
This is what is being returned to me:
{
"student_name": "Joshua",
"classes": [
"A1",
"A2",
"A3",
]
"food": {
"size": "slice",
"type": "pepperoni",
}
}
So would like to parse the array, classes, the object, food, and the string student_name, and console log them.
You need to use JSON.parse() to do it:
var myData = {
"student_name": "Joshua",
"classes": [
"A1",
"A2",
"A3",
]
"food": {
"size": "slice",
"type": "pepperoni",
}
}
var myObject = JSON.parse(myData);
console.log(myObject.student_name); //Output: Joshua
console.dir(myObject) //to see your object in console.
display a single element:
console.log(myData.classes[0]);
display all elements of an array:
var arr = myData.classes;
for(var i in arr)
{
console.log(arr[i]);
}
For more information:
About JSON.parse()
JSON.Parse() Examples
JSON is the JavaScript Object Notation, which means JSON snippets already represent JavaScript objects. You just have to parse them using:
var myObject = JSON.parse(json);
And then you can access:
var myArray = myObject.classes; //should give you an array
console.log(myArray[0]); //should print "A1"
var myFood = myObject.food //should give you a food object with size and type properties
console.log(myFood.size); //should print "slice"
so I am trying to assign json data to an array variable in d3.
Here is my json:
[
{
"Impressions": "273909",
"Clicks": "648",
"CPM": 4.6388278388278,
"Cost": 1266.4,
"CPC": 1.9543209876543,
"Campaign": "Campaign 1"
},
{
"Impressions": "974408",
"Clicks": "14571",
"CPM": 4.0175975359343,
"Cost": 3913.14,
"CPC": 0.26855672225654,
"Campaign": "Campaign 2"
},
{
"Impressions": "76751",
"Clicks": "5022",
"CPM": 8.4675,
"Cost": 643.53,
"CPC": 0.1281421744325,
"Campaign": "Campaign 3"
},
and here is my code to load the json dataset:
d3.json("DS003a_Adwords_AdPerformance_modified.json", function(error, data) {
var topData = data.sort(function(a, b){
return d3.descending(+a.cost, +b.cost);
}).slice(0,10);
topData.forEach(function (d) {
d.CampaignName = d.Campaign;
d.cost = d.Cost;
});
var cost = d3.nest()
.key(function(d) {return d.Cost;})
.entries(data); //fail
var p = d3.select("body").selectAll("p")
.data(topData)
.enter()
.append("p")
.text(function(d,i){
return (i+1) + ". " + d.CampaignName + " cost = " + cost[i];
});
I basically want to save the value of "Cost" to an array variable var cost.
But when I tried my code the result is as followed:
What should i do?
Thank you, your help is appreciated :)
You cannot use nest to directly have an array of values. The two possible output formats of nest are:
a large object
{
key1: value1,
key2: value2,
...
}
or an array of small objects
[
{ key: key1, values: value1 },
{ key: key2, values: value2 },
...
]
Neither is the one you desire. (Remember the first goal of nest: identify a set of keys, and group all pieces of data with the same key in a single batch, possibly with some transformation).
If for some reason you don't want to use your original array as suggested in the comments, then d3.map is what you're needing:
var cost = d3.map(data, function(d) {
return d.cost;
});
This is creating a copy of your cost data (if your data array changes, then you will need to run d3.map again to update your array). So you should use this array only locally if your data may not be constant. This is why in general one prefers using the original data directly, as it also saves this copy step and has less risks of tricky bugs later on.
I have an JSON array like this
var filter_value_data = [{"Status":[{"name":"Open","id":"1"},{"name":"Pending","id":"2"},{"name":"Resolved","id":"3"},{"name":"Closed","id":"4"},{"name":"Evaluation","id":"5"}]},{"Payment Status":[{"name":"Paid","id":"10"},{"name":"UnPaid","id":"11"},{"name":"Part Paid","id":"12"}]},{"Priority":[{"name":"Low","id":"6"},{"name":"Medium","id":"7"},{"name":"High","id":"8"},{"name":"Urgent","id":"9"}]}]
I have tried filter_value_data["Status"] which is obviously wrong. How do I get the JSON elements for Status using the names like Status,Payment Status?
filter_value_data is an array (having []), so use filter_value_data[0].Status to get the first element-object with property "Status".
It is always good to format your code in order to see the hierarchy of the structures:
var filter_value_data = [
{
"Status": [
{
"name": "Open",
"id": "1"
}, {
"name": "Pending",
"id": "2"
}, ...
]
}, {
"Payment Status": [
{
"name": "Paid",
"id": "10"
}, ...
]
}, {
"Priority": [
{
"name": "Low",
"id": "6"
}, ...
]
}
];
With your current JSON you can't get the elements with the name alone.
You can get Status with filter_value_data[0]['Status'] and Payment status with filter_value_data[1]['Payment Status'].
This is because the keys are in seperate objects in the array.
In order to get them with filter_value_data['Status'] you need to change your JSON to
var filter_value_data = {
"Status":[
{"name":"Open","id":"1"},
{"name":"Pending","id":"2"},
{"name":"Resolved","id":"3"},
{"name":"Closed","id":"4"},
{"name":"Evaluation","id":"5"}
],
"Payment Status":[
{"name":"Paid","id":"10"},
{"name":"UnPaid","id":"11"},
{"name":"Part Paid","id":"12"}
],
"Priority":[
{"name":"Low","id":"6"},
{"name":"Medium","id":"7"},
{"name":"High","id":"8"},
{"name":"Urgent","id":"9"}
]
};
I wrote this on my phone so it's not as well-formatted as usual. I'll change it ASAP.
With your current JSON, created a result which might be helpful for you.
JS:
$.each(filter_value_data,function(ind,val){
var sta = val.Status; // Status Object get displayed
for(var i=0;i<sta.length;i++){
var idVal= sta[i].id;
var nameVal = sta[i].name;
Statusarray.push(idVal,nameVal);
console.log(Statusarray);
}
})
FiddleDemo
You can use below code, it will return status object
filter_value_data[0]['Status']
filter_value_data[0]['Payment Status']
to get Single value you use :
filter_value_data[0]['Status'][0]['name']
If I have a JSON Object Map :
var dataItem=[{
"Lucy":{
"id": 456,
"full_name": "GOOBER, ANGELA",
"user_id": "2733245678",
"stin": "2733212346"
},
"Myra":{
"id": 123,
"full_name": "BOB, STEVE",
"user_id": "abc213",
"stin": "9040923411"
}
}]
I want to iterate through this list and access the names (i.e. Lucy, Myra ) and corresponding information
All the loops that I came across looped through the list like this :
var dataItem = [
{"Name":"Nthal","Class":3,"SubjectName":"English "},
{"Name":"Mishal","Class":4,"SubjectName":"Grammer"},
{"Name":"Sanjeev","Class":3,"SubjectName":"Social"},
{"Name":"Michal","Class":5,"SubjectName":"Gk"},
]
for(x in dataItem)
{
alert(dataItem[x].Name);
alert(dataItem[x].Class);
alert(dataItem[x].SubjectName);
}
Thanks in advance
What you have there is not JSON, maybe because you've already parsed it. You have is an array consisting of a single object, with names for its keys. Regardless, I'll show you how to access that data:
var data = dataItem[0];
for(name in data) {
alert(name);
alert(data[name].id);
alert(data[name].full_name);
}
for (var x in dataItem[0]) {
if (dataItem[0].hasOwnProperty(x)) {
console.log(x);
}
}
http://jsfiddle.net/B44LW/
If you want other properties, then you can use the bracket notation:
dataItem[0][x].id