I’m attempting to find the number of occurrences based on input value for ownerId in the JavaScript Json Object below. If the ownerId is the number "1" the result should be three since the ownerId appears 3 times.
ownerID: 3
Here is what I have so far…
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"
}
]
}
]
}
Am I going about this the right way using find and reduce?
2
Answers
You are almost there, what you need to do is count across multiple
jsonArrays
and also within theinfo
sLook at the code below, I have commented it appropriately to make it verbose.
Hope it helps.
You can also use forEach loop or reduce as given in other answer both method works fine.