我是Javascript和JSON的新手。我想通过Javascript获取以下JSON值。我需要检索"登录"价值并加上" a"," d"和" c"分别。我设法得到了#34;登录"价值,但我无法弄清楚如何检索" a"," d"和" c"值。
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"
}
}
]
答案 0 :(得分:2)
您可以使用数组方法map和reduce。 jQuery并不是必需的。
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
})
答案 1 :(得分:2)
试试这个会起作用:
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。用于循环
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。使用数组映射方法
var weekData = data[0].weeks;
var returnData = weekData.map(function(e) {
return {
a: e.a,
d: e.d,
c: e.c
}
})
console.log(returnData);