我有这样的收藏:
{ "items": [
{
"id": "123",
"meta": {
"activity": 2
}
},
{
"id": "13423",
"meta": {
"activity": 4
}
}
]}
鉴于该收藏,我如何获得该收藏的全部活动?在上述情况下,结果为6。
我正在使用主干和下划线。
您正在使用underscore.js,因此您可以使用一些好的工具。查看_.map()开始使用。
var flatArray = _.map(collection.items, function(x){return x.meta.activity;});
// should return: [2,4]
然后您可以使用_.reduce()将其转换为单个值。
var total = _.reduce(flatArray, function(memo, num) {return memo + num;}, 0);
// should return: 6
underscore.js中还有很多其他很棒的工具,值得一看的是还有其他工具对您也有用。
在下划线中,您可以使用reduce函数,该函数将使用给定的迭代器函数将值列表简化为单个值。
var myCollection = { "items": [
{
"id": "123",
"meta": {
"activity": 2
}
},
{
"id": "13423",
"meta": {
"activity": 4
}
}
]};
var totalActivity = _.reduce(myCollection.items, function(memo, item){ return memo + item.meta.activity; }, 0);