我试图根据下面的JavaScript Json Object中的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"
}
]
}
]
}
型
我使用find和reduce的方法正确吗?
3条答案
按热度按时间58wvjzkj1#
您几乎已经完成了,您需要做的是在多个
jsonArrays
上计数,并在info
内计数看看下面的代码,我已经适当地注解了它,使它变得冗长。希望它能有所帮助。
字符串
sg3maiej2#
你也可以使用forEach循环或reduce,就像在其他答案中给出的那样,这两种方法都很好。
字符串
6qfn3psc3#
如果你熟悉@ut8pia/classifier库,你就会知道,通过使用
queue
和searchspace
作为函数返回每个已探索对象的所有子对象,探索嵌套对象变得很简单。字符串
方法
search(space)
导航root
节点的所有后代。要返回的是迭代的形式定义,提供进一步的方法来限制,组合,转换和解析迭代。让我们应用这个称为“搜索和选择”模式的范例,来定义一个函数
n(key, value, root)
,该函数计算具有指定key
属性的value
嵌套对象的出现次数。型
方法
which(predicate)
将search
限制为满足predicate
的对象,而方法what(op, start)
解析search
。这些方法类似于Array类中的方法filter(predicate)
和reduce(op, start)
,但设计为即使在涉及无限迭代的情况下也适用(请参阅图书馆的在线文档)。您可以通过以下方式检查建议解决方案的有效性:
型