stackyyflow stackyyflow - 1 month ago 10
JSON Question

Retrieving JSON object value from Javascript

I am new to Javascript and JSON. I want to get the following JSON values via Javascript. I need to retrieve the "login" value and add up the "a", "d" and "c" respectively. I managed to get "login" value but I couldn't figure out how do i retrieve "a", "d" and "c" values.

var data = JSON.parse(text);
$.each(data, function(i, v) {
var login = v.login; // Get "login"
var commits = 0;
var additions = 0;
var deletions = 0;
var contributions = 0;

$.each(data, function(j, w) {
commits += w.c; // Get "c"
additions += w.a; // Get "a"
deletions += w.d; // Get "d"
});
});


JSON:

[
{
"total": 2,
"weeks": [
{
"w": 1214092800,
"a": 0,
"d": 0,
"c": 0
},
{
"w": 1474761600,
"a": 0,
"d": 0,
"c": 0
},
{
"w": 1476576000,
"a": 0,
"d": 0,
"c": 0
}
],
"author": {
"login": "ramiro"
}
}
]

Answer

Try this it will work :

JSON :

var data = [ { "total": 2, "weeks": [ { "w": 1214092800, "a": 0, "d": 0, "c": 0 }, { "w": 1474761600, "a": 0, "d": 0, "c": 0 }, { "w": 1476576000, "a": 0, "d": 0, "c": 0 } ], "author": { "login": "ramiro" } } ];

1. Using for in loop

var weekData = data[0].weeks; 
for (var i in weekData) {
 console.log(data[0].weeks[i].a,data[0].weeks[i].d,data[0].weeks[i].c);
}

2. using Array map method

var weekData = data[0].weeks; 

var returnData = weekData.map(function(e) {
return {
          a: e.a,
          d: e.d,
          c: e.c
        }
})

console.log(returnData);

Working fiddle : https://jsfiddle.net/ry49dz61/1/