如何计算以下json中非空dailyemails
的数量?
{
"templates":[
{
"id":"2c1d99d9b6b2fb417601d24c10c9b041a7d6f37b",
"dailyemails":[
"[email protected]",
"[email protected]"
],
"name":"Registration Report"
},
{
"id":"45s4dsf4qdgze5zef1z3e2f1zevcd5s6sdfsdfsdf",
"dailyemails":[
],
"name":"Presentation"
},
{
"id":"7d7cc642ca13cc4a998cad364dfe8e623fd95ae3",
"dailyemails":[
"[email protected]"
],
"name":"Live Report"
}
]
}
我目前正在读取节点总数
Object.keys(myArr).length
:function metaInfo (id, cb){
var URL = someURLhere
var count = []
fs.readFile(__dirname +'/' + URL+'/myFile.json', 'utf8', function (err, data) {
if (err) cb (err);
obj = JSON.parse(data);
var myArr = obj.nodes;
count.push(Object.keys(myArr).length);
cb(null, count)
});
};
如何读取非空
dailyemails
的数量? 最佳答案
您可以这样使用reduce
:
var count = myArray.reduce(function(c, o) {
return c + (o.dailyemails.length? 1: 0);
}, 0);
使用箭头功能甚至更短:
var count = myArray.reduce((c, o) => c + (o.dailyemails.length? 1: 0), 0);