
本文介绍如何在嵌套多层的 json 结构中,准确统计某个 ownerid 值在整个数据集中出现的总次数,涵盖数组遍历、条件过滤与累加计数的核心逻辑,并提供可直接运行的健壮示例代码。
本文介绍如何在嵌套多层的 json 结构中,准确统计某个 ownerid 值在整个数据集中出现的总次数,涵盖数组遍历、条件过滤与累加计数的核心逻辑,并提供可直接运行的健壮示例代码。
在处理类似 jsonResponse.jsonArray 这样包含多个对象、每个对象又包含 info 数组的嵌套 JSON 数据时,目标是跨所有层级统一统计某 ownerId 的总出现次数(例如 ownerId: 1 共出现 3 次)。你原代码中存在几个关键问题:
- ❌
find()仅返回第一个匹配项,无法用于计数; - ❌
reduce内部误用result[inputValue](inputValue是数字,不是属性名); - ❌ 未遍历
jsonArray中的每一个元素,仅操作了[0].info; - ❌ 属性名拼写错误(如
ownderID应为ownerId)。
✅ 正确思路是:对 jsonArray 整体执行 reduce,对每个元素的 info 数组使用 filter() 筛出匹配的项,再通过 .length 获取该组内数量,最后累加。
以下是优化后的完整实现:
const jsonResponse = {
"jsonArray": [
{
"info": [
{ "ownerId": 1, "carType": "Nissan", "houseType": "Rancher" },
{ "ownerId": 1, "carType": "Ford", "houseType": "Trailer" }
],
"familyInfo": { "kids": 1, "tuition": "yes", "parentId": 7 }
},
{
"info": [ { "ownerId": 3, "carType": "Nissan", "houseType": "Single" } ],
"familyInfo": { "kids": 4, "tuition": "no", "parentId": 11 }
},
{
"info": [ { "ownerId": 1, "carType": "Chevy", "houseType": "TownHome" } ]
}
]
};
// ✅ 定义要查找的 ownerId
const searchOwnerId = 1;
// ✅ 使用 reduce 遍历 jsonArray,累加每个 info 数组中匹配的元素数量
const totalCount = jsonResponse.jsonArray.reduce((sum, item) => {
// 确保 item.info 存在且为数组,避免运行时错误
const infoArray = Array.isArray(item.info) ? item.info : [];
const matchedCount = infoArray.filter(obj => obj.ownerId === searchOwnerId).length;
return sum + matchedCount;
}, 0);
console.log(`ownerId ${searchOwnerId} appears ${totalCount} time(s).`); // 输出:ownerId 1 appears 3 time(s).
? 关键要点说明:
- 使用
Array.isArray(item.info)做防御性检查,防止因某条数据缺失info字段导致报错; -
filter(...).length比reduce或forEach更简洁安全,语义清晰; - 初始值设为
0,确保累加从零开始; - 严格使用
===进行全等比较,避免类型隐式转换引发误判(如1 == "1"为true,但业务中通常需精确匹配)。
? 扩展建议:
若需统计所有 ownerId 的频次分布(如 {1: 3, 3: 1}),可将 reduce 改为对象累加器:
const frequencyMap = jsonResponse.jsonArray.reduce((acc, item) => {
const infoArray = Array.isArray(item.info) ? item.info : [];
infoArray.forEach(obj => {
const id = obj.ownerId;
acc[id] = (acc[id] || 0) + 1;
});
return acc;
}, {});
console.log(frequencyMap); // { '1': 3, '3': 1 }
此方案结构清晰、健壮性强,适用于任意深度的同类嵌套结构,是生产环境中推荐的统计模式。











