![](/img/trans.png)
[英]how to count number of items that users answered in the quiz using Json array
[英]Count the number of items in json with conditions
我想計算符合某些條件的JSON項目數組中的項目數。 我的數組看起來像這樣:
array = [{
name: 'Bob',
age: 24
},
....,
{
name: 'Mary',
age: 23
}]
我試圖讓表達式像我的數據庫請求一樣簡單優雅,而不是遍歷整個數組:
db.myCollection.find({ age: 23 }).count()
有沒有最好的做法? 我在考慮使用下划線庫,但我無法找到我要找的東西。
非常感謝您的幫助。
那么,您可以在沒有任何第三方庫的情況下執行此操作,也無需循環:
array.filter(function(value) { return value.age === 23 }).length;
而對於ES6,它甚至變得更加簡潔
array.filter(value => value.age === 23).length;
正如我在操作中提到的,看起來你正在尋找_.size
_.chain(json)
.find({age: 23})
.size()
.value();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.