dausdashsan
dausdashsan

Reputation: 251

Query through Json object

This is my JSON:

[{"Id":1,"Order":1,"IsDone":true,"Text":"abc","Date":"6/14/2014"},
 {"Id":2,"Order":2,"IsDone":false,"Text":"cde","Date":"6/15/2014"},
 {"Id":3,"Order":3,"IsDone":false,"Text":"fgh","Date":"6/16/2014"}]

What would be the most efficient way to get the count of IsDone == true?

Upvotes: 1

Views: 94

Answers (5)

Mourice
Mourice

Reputation: 597

Use grep fron jquery

var selectedArray = [{"Id":1,"Order":1,"IsDone":true,"Text":"abc","Date":"6/14/2014"},
{"Id":2,"Order":2,"IsDone":false,"Text":"cde","Date":"6/15/2014"},
{"Id":3,"Order":3,"IsDone":false,"Text":"fgh","Date":"6/16/2014"}]



selectedArray = jQuery.grep(selectedArray, function (el) { return el.IsDone == true;   });

 alert(selectedArray.length);

where seletedArray is your actual array

http://jsfiddle.net/QxV6K/

Upvotes: 1

abhinsit
abhinsit

Reputation: 3272

In case you're trying to access an item from the example structure by id or name, without knowing it's position in the array, the easiest way to do it would be to use underscore.js library:

    var data =   [{"Id":1,"Order":1,"IsDone":true,"Text":"abc","Date":"6/14/2014"},{"Id":2,"Order":2,"IsDone":false,"Text":"cde","Date":"6/15/2014"},{"Id":3,"Order":3,"IsDone":false,"Text":"fgh","Date":"6/16/2014"}];

    var allDesiredElements = _.filter(data, function(item) {
      return item.IsDone === true;
    });

//for length use
console.log(allDesiredElements.length);

Upvotes: 0

chandu
chandu

Reputation: 2276

try this one

 var obj = [{"Id":1,"Order":1,"IsDone":true,"Text":"abc","Date":"6/14/2014"},
    {"Id":2,"Order":2,"IsDone":false,"Text":"cde","Date":"6/15/2014"},
    {"Id":3,"Order":3,"IsDone":false,"Text":"fgh","Date":"6/16/2014"}]

    var count = 0;
    for(i=0;i<obj.length;i--){
      count += (obj[i].IsDone) ? 1 : 0;
    }

Upvotes: 0

Diana Nassar
Diana Nassar

Reputation: 2303

var data = [{"Id":1,"Order":1,"IsDone":true,"Text":"abc","Date":"6/14/2014"},{"Id":2,"Order":2,"IsDone":false,"Text":"cde","Date":"6/15/2014"},{"Id":3,"Order":3,"IsDone":false,"Text":"fgh","Date":"6/16/2014"}];

var count = data.filter(function (el) {
  return (el.IsDone === true);
});

alert(count.length);

DEMO

Upvotes: 0

Mr.Cocococo
Mr.Cocococo

Reputation: 1451

You can use plain javascript iteration:

var a=[{"Id":1,"Order":1,"IsDone":true,"Text":"abc","Date":"6/14/2014"},{"Id":2,"Order":2,"IsDone":false,"Text":"cde","Date":"6/15/2014"},{"Id":3,"Order":3,"IsDone":false,"Text":"fgh","Date":"6/16/2014"}]

var ct=0;
a.forEach(function(entry) {
    if(entry.IsDone)ct++;
});
alert(ct);

Upvotes: 3

Related Questions