最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Count the number of items in json with conditions - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited May 22, 2014 at 9:59 axwcode 7,8247 gold badges32 silver badges41 bronze badges asked Mar 25, 2014 at 21:42 SpearfisherSpearfisher 8,78324 gold badges74 silver badges125 bronze badges 3
  • Can you be a little clearer on what kind of conditions you are talking about? Is it just the existence of certain keys in the JSON object or are they actual conditions of certain keys being equal to certain values? – aug Commented Mar 25, 2014 at 21:46
  • Isn't Array.prototype.filter() an option? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – jarandaf Commented Mar 25, 2014 at 21:46
  • If you're using underscore there's _.size(..) – megawac Commented Mar 25, 2014 at 21:49
Add a comment  | 

2 Answers 2

Reset to default 20

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();
发布评论

评论列表(0)

  1. 暂无评论