2015-07-20 39 views
1

我正在運行查詢並獲取表示特定組中人員數量的值。我的數據回來是這樣的:從返回的JSON中獲取運行總數/百分比

0: Object 
    count: 10 
    grp: 1 
1: Object 
    count: 20 
    grp: 2 
2: Object 
    count: 30 
    grp: 3 
3: Object 
    count: 40 
    grp: 4 

我想要得到的是運行總計並保存在一個數組,所以我會像這樣結束了:

[[0,10],[1,30],[2,60],[3,100]]

這裏的我的開始,但不知道我需要放在我的push中。

d1_1 = []; 
$.each(data.rows, function(index, value){ 
d1_1.push(***what goes here?***); 
}); 

回答

2

這是否有訣竅?

var input = [{count:10, grp:1},{count:20,grp:2},{count:30,grp:3},{count:40,grp:4}]; 
counter = 0; 
var d1_1 = []; 
jQuery.each(input, function(index, elem) { 
counter += elem.count; 
d1_1.push([index,counter]); 
}); 
0
var json = [{count: 10, group: 1},{count: 20, group: 2}, {count: 30, group: 3},{count: 40, group: 4}]; 
var myJSONArray = []; 
var myArray = []; 

$.each(json, function(index, value){  
    //Results in [{count: 10, group: 1}, {count: 20, group: 2}, etc] 
    var temp = {"count": value.count, "group": value.group}; 
    myJSONArray.push(temp); 
    //console.log(myJSONArray); 

    //Results in [10, 1], [20, 2], etc 
    myArray.push([value.count, value.group]); 
    //console.log(myArray); 
}); 

http://jsfiddle.net/z5davs6h/

如果你想索引推入你的數組,你可以做些事情是這樣

var json = [{count: 10, group: 1},{count: 20, group: 2}, {count: 30, group: 3},{count: 40, group: 4}]; 
var myArray = []; 

$.each(json, function(index, value){  
    //Results in [0, 10], [1, 20], etc 
    myArray.push([index, value.count]); 
    //console.log(myArray); 
}); 
0
var json = [{count: 10,grp: 1}, {count: 11,grp: 2}], 
     result = [], 
     temp = []; 

    for (var i in json) { 
     temp.push(json[i].grp, json[i].count); 
     result.push(temp); 
     temp = []; 
    }