【问题标题】:Count the number of all specific keys (or values) in JSON array计算 JSON 数组中所有特定键(或值)的数量
【发布时间】:2022-12-03 13:38:38
【问题描述】:
我有一个像这样的大型嵌套 JSON 对象,我想计算整个对象中 pets 的数量。我们怎样才能做到这一点?我试过 Object.keys(obj[0]).length 但没有成功达到预期的结果。另外,我怎样才能更深入地研究数组以计算一些嵌套值,例如 pet 中的 color?
在 JavaScript 或 Angular 中使用多级数组的好教程是什么?
obj = [
{
"person": {
"name": "a",
},
"pet": {
"name": "1"
}
},
{
"person": {
"name": "b",
},
"pet": {
"name": "2",
"color": "black",
}
},
{
"person": {
"name": "c",
},
"pet": {
"name": "3",
"color": "red",
}
}
]
【问题讨论】:
标签:
javascript
arrays
json
angular
【解决方案1】:
let pets = 0;
obj.map( item => {
if(item.pet) {
pets += 1;
}
})
【解决方案2】:
用宠物属性和宠物的颜色属性过滤数组并进行数组计数。
let obj = [
{
"person": {
"name": "a",
},
"pet": {
"name": "1"
}
},
{
"person": {
"name": "b",
},
"pet": {
"name": "2",
"color": "black",
}
},
{
"person": {
"name": "c",
},
"pet": {
"name": "3",
"color": "red",
}
}
];
let petItemCount = obj.filter(x => x["pet"]).length;
console.log(petItemCount);
let petItemWithColorCount = obj.filter(x => x["pet"] && x["pet"]["color"]).length;
console.log(petItemWithColorCount);
如果 pet 值可能是 null 或者宠物的 color 可能是 null,
let petItemCount = obj.filter(x => x["pet"] != undefined).length;
console.log(petItemCount);
let petItemWithColorCount = obj.filter(x => x["pet"] && x["pet"]["color"] != undefined).length;
console.log(petItemWithColorCount);
【解决方案3】:
听起来减少会很合适:
colors = obj.reduce(
(sum, { pet }) => pet.color !== undefined ? ++sum : sum,
0)); // -> initial count value