I have large nested json object like this, and I want to count the number of pets in the whole object. How can achieve that? I've tired Object.keys(obj[0]).length but not successful of the desired result. Also how can I go deeper into array for counting for example some nested value like color in pet?
What is the good tutorial for working with multi level arrays in JavaScript or Angular?
obj = [
{
"person": {
"name": "a",
},
"pet": {
"name": "1"
}
},
{
"person": {
"name": "b",
},
"pet": {
"name": "2",
"color": "black",
}
},
{
"person": {
"name": "c",
},
"pet": {
"name": "3",
"color": "red",
}
}
]
CodePudding user response:
Filter the array with pet property and pet's color property and perform array count.
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);
CodePudding user response:
let pets = 0;
obj.map( item => {
if(item.pet) {
pets = 1;
}
})
CodePudding user response:
Sounds like reducing would be a fit:
numberOfPetColors = obj.reduce(
(sum, { pet }) => pet.color !== undefined ? sum : sum,
0)); // -> starting count value
If using lodash you can also use sumBy
:
_.sumBy(obj, (arrayEntry) => arrayEntry.pet.color)