Reputation: 15555
[{
"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
}]
This is my sample json object (it can have so many values but the format is like this)how can i iterate this sample to get the value of nature only once per id i wanted to have a counter in which i want to count how many nature with value 1
and with value 0
(the only value of nature is 1
and 0
) for every id
. The id
with be the unique identifying body.
What i want is to be able to count the nature for every id example out put will be
ID:2015-07-002
Nature0:0
Nature1:1
Upvotes: 0
Views: 144
Reputation: 3760
This is what you are looking for
CODE
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
}];
$(":button").click(function(){
var zeros=0;
var ones=0;
$(data).each(function(i,v){
if($(this)[0].nature==0)
{
zeros++;
}
if($(this)[0].nature==1)
{
ones++;
}
});
alert("ZEROS:"+zeros+"\r\nONES:"+ones);
});
Upvotes: 1
Reputation: 3850
Add the id in an array then check that array if you are iterating the array.
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);
}
}
});
Upvotes: 1
Reputation: 781004
Make an object whose keys are the id's, and the value is an object with a counter for zeroes and ones.
Also, $(data).each()
is used for iterating over collections of jQuery elements. To iterate over an array, use $.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']);
}
Upvotes: 2