javascript获取非空JSON子数组的计数

时间:2017-04-26 15:00:34

标签: javascript arrays json

如何计算以下json中非空dailyemails的数量?

{
   "templates":[
      {
         "id":"2c1d99d9b6b2fb417601d24c10c9b041a7d6f37b",
         "dailyemails":[
            "saaa@aa.com",
            "aaa.aaa@gmail.com"
         ],
         "name":"Registration Report"             
      },
      {
         "id":"45s4dsf4qdgze5zef1z3e2f1zevcd5s6sdfsdfsdf",
         "dailyemails":[
         ],
         "name":"Presentation"             
      },
      {
         "id":"7d7cc642ca13cc4a998cad364dfe8e623fd95ae3",
         "dailyemails":[
            "saaa@ss.com"
         ],
         "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的数量?

4 个答案:

答案 0 :(得分:2)

filter所有空值

var count = obj.templates.filter(item => item.dailyemails.length).length

答案 1 :(得分:2)

您可以使用filter,而不是使用reduce创建数组然后获取长度。这与filter没有相同的开销,因为您存储的唯一内容是临时变量p中的计数器。



var x = {
   "templates":[
      {
         "id":"2c1d99d9b6b2fb417601d24c10c9b041a7d6f37b",
         "dailyemails":[
            "saaa@aa.com",
            "aaa.aaa@gmail.com"
         ],
         "name":"Registration Report"             
      },
      {
         "id":"45s4dsf4qdgze5zef1z3e2f1zevcd5s6sdfsdfsdf",
         "dailyemails":[
         ],
         "name":"Presentation"             
      },
      {
         "id":"7d7cc642ca13cc4a998cad364dfe8e623fd95ae3",
         "dailyemails":[
            "saaa@ss.com"
         ],
         "name":"Live Report"
      }

   ]
}

alert(x["templates"].reduce(function(p, e)
              {
                if(e["dailyemails"].length !==0)
                    p+=1;
                return p;
              },0));




答案 2 :(得分:2)

您可以像这样使用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);

答案 3 :(得分:2)

您需要使用数组>>> new_name #variable not existing yet Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> new_name NameError: name 'new_name' is not defined >>> globals()["new_name"]="new value" >>> print(new_name) new value 方法。

filter