我正在构建一个 JSON 响应,如下所示:
{
"G5LDUHRPEEA6B-39CFBWYA": [],
"JMSK0DKOEEA0UXMY750O3W": [],
"ISVN8JF1EEAD3W398ZNOSA": [
{
"delloData": "1478644629",
"ref": "75",
"dataType": "String",
"somePart": LA,
"hello": "OUTSIDE"
},
{
"delloData": "1478644629",
"ref": "75",
"dataType": "String",
"somePart": Chicago,
"hello": “Inside"
},
{
"delloData": "1478644629",
"ref": "75",
"dataType": "String",
"somePart": Austin,
"hello": “Inside"
}
],
"VRG0IJF1EEAD3W398ZNOSA": [{
"delloData": "1478644629",
"ref": "75",
"dataType": "String",
"somePart": Chicago,
"hello": “Inside"
},
{
"delloData": "1478644629",
"ref": "75",
"dataType": "String",
"somePart": Austin,
"hello": “Inside"
}],
"OGAESJF2EEAD3W398ZNOSA": [],
"SC9OMJF2EEAD3W398ZNOSA": []
}
我想计算数组中的项目总数,包括内部数组,并忽略内部数组是否为空,如“SC9OMJF2EEAD3W398ZNOSA”:[] 我尝试了 _.size(collection) 但我需要知道如何删除空的内部尺寸。提前致谢
最佳答案
您可以使用 Array.prototype.reduce 并循环来总结数组的长度 - 请参阅下面的演示:
var object={"G5LDUHRPEEA6B-39CFBWYA":[],"JMSK0DKOEEA0UXMY750O3W":[],"ISVN8JF1EEAD3W398ZNOSA":[{"delloData":"1478644629","ref":"75","dataType":"String","somePart":"LA","hello":"OUTSIDE"},{"delloData":"1478644629","ref":"75","dataType":"String","somePart":"Chicago","hello":"Inside"},{"delloData":"1478644629","ref":"75","dataType":"String","somePart":"Austin","hello":"Inside"}],"VRG0IJF1EEAD3W398ZNOSA":[{"delloData":"1478644629","ref":"75","dataType":"String","somePart":"Chicago","hello":"Inside"},{"delloData":"1478644629","ref":"75","dataType":"String","somePart":"Austin","hello":"Inside"}],"OGAESJF2EEAD3W398ZNOSA":[],"SC9OMJF2EEAD3W398ZNOSA":[]}
var result = Object.keys(object).reduce(function(p,c){
p+= object[c].length;
return p;
},0);
console.log(result);
关于javascript - 计算 Json 数组中项目的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40871213/