简体   繁体   中英

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.

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;

As I mentioned in op, it seems like you're looking for _.size

_.chain(json)
 .find({age: 23})
 .size()
 .value();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM