如何使用Javascript从JSON获得总数

时间:2013-08-14 10:29:34

标签: javascript jquery json

我需要从JSON数据中获取每个列的总数。下面是我想要获得每列总数的JSON数据。

[
 {"campaign":"MD001","seen":650,"taken":62,"eligible":542,"total":1000,"ind":"E"},
 {"campaign":"MD002","seen":550,"taken":52,"eligible":342,"total":1000,"ind":"E"},
 {"campaign":"MD003","seen":800,"taken":69,"eligible":642,"total":1000,"ind":"W"},
 {"campaign":"MD004","seen":500,"taken":62,"eligible":527,"total":1000,"ind":"E"},
 {"campaign":"MD005","seen":350,"taken":29,"eligible":992,"total":1000,"ind":"w"},
 {"campaign":"MD006","seen":550,"taken":52,"eligible":342,"total":1000,"ind":"W"}
]

高于他们的手段是“符合条件的”&每个“符合条件的”都有不同的价值,因此我需要从上述数据中获得“合格”的总数。

2 个答案:

答案 0 :(得分:4)

你必须计算它:

var data = // your json data
var total = 0;
for(var i = 0; i < data.length; i++){
    total += parseInt(data[i].eligible);        
}

这是一个小提琴http://jsfiddle.net/CVpxR/

答案 1 :(得分:2)

你可以这样做:

data = [
    {"campaign":"MD001","seen":650,"taken":62,"eligible":542,"total":1000,"ind":"E"},
    {"campaign":"MD002","seen":550,"taken":52,"eligible":342,"total":1000,"ind":"E"},
    {"campaign":"MD003","seen":800,"taken":69,"eligible":642,"total":1000,"ind":"W"},
    {"campaign":"MD004","seen":500,"taken":62,"eligible":527,"total":1000,"ind":"E"},
    {"campaign":"MD005","seen":350,"taken":29,"eligible":992,"total":1000,"ind":"w"},
    {"campaign":"MD006","seen":550,"taken":52,"eligible":342,"total":1000,"ind":"W"}
]

var total = 0;

$.each(data, function(index, item){
    total = total + item.eligible;
});

工作小提琴:http://jsfiddle.net/2A9qv/2/