Reputation: 441
I have following JSON object and want to get the value of the date. 0.0 is "Off" status and 2.0 of "On" Status. For my project requirement, I want to take out as follow:
Date ="2017-12-01" Active = 73% Off = 26%
How can I achieve that scenario for the given JSON object?
{
"2017-12-02": {
"0.0": 1.0
},
"2017-12-01": {
"2.0": 0.7379912663755459,
"0.0": 0.26200873362445415
}
}
Upvotes: 1
Views: 60
Reputation: 875
You can use JSON.parse
to parse the string to a JSON object(if needed), and then use it like any other object, for example use the for..in loop to iterate through dates:
var jso = json.Parse(str)
for (let dat in jso) {
var out = "Date = \"" + dat + "\" ";
jso[dat]["0.0"] &&
(out += ("Active = " + parseInt(jso[dat]["0.0"] * 100) + "% "));
jso[dat]["2.0"] &&
(out += ("Off = " + parseInt(jso[dat]["2.0"] * 100) + "% "));
console.log(out);
}
Upvotes: 0
Reputation: 126
Try to use this:
var obj = {
"2017-12-02":{
"0.0":1.0
},
"2017-12-01":{
"2.0":0.7379912663755459,
"0.0":0.26200873362445415
}
}
var objectKeys = Object.keys (obj);
for (var i = 0; i < objectKeys.length; i ++) {
var act = obj [objectKeys [i]]["2.0"];
var off = obj [objectKeys [i]]["0.0"];
console.log ("Date=" + objectKeys [i] + " Active=" + ((act ? act : 0) * 100).toFixed (0) + "% Off=" + ((off ? off : 0) * 100).toFixed (0) + "%");
}
Upvotes: 3
Reputation: 22524
You can use array#map
to generate the output and Object.keys()
to iterate through the keys.
var obj = {"2017-12-02":{"0.0":1.0},"2017-12-01":{"2.0":0.7379912663755459,"0.0":0.26200873362445415}},
result = Object.keys(obj).map(k => `Date = ${k} Active = ${Math.trunc((obj[k]["2.0"] || 0)*100)}% Off = ${Math.trunc((obj[k]["0.0"] || 0)*100)}%`);
console.log(result);
Upvotes: 2