1

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"
    }
  }
]

2 Answers 2

2

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/

Sign up to request clarification or add additional context in comments.

3 Comments

Using array filter is not a solution...you try seeing what weekData has...The result of weekData and returnData is same
Yup this is fine...I think this is the best approach as of now
@PankajKumar Thanks a lot for the compliment..you can upvote this answer if you think it will be benfitial for others.
2

You could use array method map and reduce. jQuery is not quite necessary.

var retrieved = data.map(function(v) {
  var ret = v.weeks.reduce(function(a, b) {
    return {
      a: a.a + b.a,
      d: a.d + b.d,
      c: a.c + b.c
    }
  })
  ret.login = v.author.login
  return ret
})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.