迭代json数组只获得一次jquery值

时间:2015-07-07 07:47:03

标签: jquery json

[{
    "id": "2015-07-002",
    "class": "7",
    "nature": "1",
    "resolution": "res1",
    "mstatus": "1",
    "cstatus": null,
    "astatus": null
}, {
    "id": "2015-07-002",
    "class": "7",
    "nature": "1",
    "resolution": "res1",
    "mstatus": "2",
    "cstatus": null,
    "astatus": null
}]

这是我的示例json对象(它可以有这么多的值,但格式是这样的)我怎么能迭代这个样本,每个id只获得一次自然的值我想拥有一个我想要的计数器使用value 1value 0(自然的唯一值为10)计算每个id的自然数量。 id是唯一的识别机构。

我想要的是能够计算出每个id例子的性质

ID:2015-07-002 Nature0:0 Nature1:1

3 个答案:

答案 0 :(得分:2)

创建一个键为id的对象,该值为具有零和1计数器的对象。

此外,$(data).each()用于迭代jQuery元素的集合。要迭代数组,请使用$.each()

var counters = {}
$.each(data, function() {
    var id = this.id;
    if (!counters[id]) {
        counters[id] = {"0" : 0, "1", 0};
    }
    counters[id][this.nature]++;
}
for (id in counters) {
    console.log(id);
    console.log('  Nature0 ' + counters[id]['0']);
    console.log('  Nature1 ' + counters[id]['1']);
}

答案 1 :(得分:1)

这就是你要找的东西

DEMO

<强> CODE

Valeurs

答案 2 :(得分:1)

在数组中添加id,然后在迭代数组时检查该数组。

var nature = [];

var data=[{
    "id": "2015-07-002",
    "class": "7",
    "nature": "1",
    "resolution": "res1",
    "mstatus": "1",
    "cstatus": null,
    "astatus": null
}, {
    "id": "2015-07-002",
    "class": "7",
    "nature": "1",
    "resolution": "res1",
    "mstatus": "2",
    "cstatus": null,
    "astatus": null
}];

var nature0 = 0;
var nature1 = 0;
$.each(data, function(index , value){
if ($.inArray(value.id, nature) == -1) {
 nature.push(value.id);
if(value.nature == '0'){
nature0++;
console.log(nature0);
}else if(value.nature == '1'){
nature1++;

console.log(nature1);
}


}
});

Sample