我正在尝试根据下面的 JavaScript Json 对象中的ownerId 输入值查找出现次数。如果ownerId 是数字“1”,则结果应该是3,因为ownerId 出现了3 次。
ownerID: 3
这是我到目前为止所拥有的...
let inputValue = 1;
let return = "";
const result = jsonResponse.jsonArray[0].info.find(
(arr) => arr.ownderID === inputValue; );
var data = jsonResponse.jsonArray[0].info
.reduce((counts, result) => {
const inputItem = result[inputValue];
counts[inputItem] = (counts[inputItem] || 0) + 1;
return counts;
}, {
});
return = data;
JSON...
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"
}
]
}
]
}
我是否可以使用查找和归约以正确的方式解决这个问题?
你就快到了,你需要做的就是数多个
jsonArrays
以及在 info
s 内
看下面的代码,我已经对其进行了适当的注释以使其更加详细。 希望有帮助。
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"
}]
}
]
}
// what to search for?
const searchOwnerId = 1;
// reduce to count owner id across multiple items in the list
const counts = jsonResponse.jsonArray.reduce((acc, item) => {
// count the owner ids inside the infos
// filter for the ownerId and length works perfect
acc += item.info.filter(
({ownerId}) => ownerId == searchOwnerId
).length
return acc
// start reduce with a zero
}, 0);
// final output
console.log(counts)