Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of items in json with conditions

I'd like to count the number of items in an array of JSON items that match some conditions. My array look like this:

array = [{
            name: 'Bob',
            age: 24
           },
          ....,
          {
            name: 'Mary',
            age: 23
           }]

Rather than looping through the whole array I am trying to get an expression as simple an as elegant as my database request:

db.myCollection.find({ age: 23 }).count()

Is there any best practice? I was thinking of using the underscore library but I couldnt find what I am looking for.

Many thanks for your help.

like image 263
Spearfisher Avatar asked Mar 25 '14 21:03

Spearfisher


People also ask

How do you find the number of items in a JSON array?

JsonArray::size() gets the number of elements in the array pointed by the JsonArray . If the JsonArray is null, this function returns 0 . Internally, this function walks a linked-list to count the elements, so its time complexity is O(n).

Can you do calculations in JSON?

No, you'll not be able to do computations inside json. The data would need to be mutated elsewhere and then sent.

How many JSON objects are represented?

JSON defines only two data structures: objects and arrays. An object is a set of name-value pairs, and an array is a list of values. JSON defines seven value types: string, number, object, array, true, false, and null.


1 Answers

Well, you can do this without any 3rd party library and also without looping:

array.filter(function(value) { return value.age === 23 }).length;

And with ES6 it even becomes more terse

array.filter(value => value.age === 23).length;
like image 125
Christoph Avatar answered Sep 20 '22 13:09

Christoph