dentist
dentist

Reputation: 244

Count the number of all specific keys (or values) in JSON array

I have a large nested JSON object like this, and I want to count the number of pets in the whole object. How can we achieve that? I've tried Object.keys(obj[0]).length but have not been successful in the desired result. Also, how can I go deeper into the array for counting for example some nested value like color in pet?

What is a 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",
          }
        }
]

Upvotes: 0

Views: 1782

Answers (3)

Yong Shun
Yong Shun

Reputation: 51485

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);

In case the pet value is possibly null or pet's color is possibly null,

let petItemCount = obj.filter(x => x["pet"] != undefined).length;
console.log(petItemCount);

let petItemWithColorCount = obj.filter(x => x["pet"] && x["pet"]["color"] != undefined).length;
console.log(petItemWithColorCount);

Upvotes: 1

Alejandro Camba
Alejandro Camba

Reputation: 988

Sounds like reducing would be a fit:

colors = obj.reduce(
 (sum, { pet }) => pet.color !== undefined ? ++sum : sum, 
0)); // -> initial count value

Upvotes: 0

Soft Technoes
Soft Technoes

Reputation: 1115

let pets = 0;
obj.map( item => {
  if(item.pet) {
    pets += 1;
  }
})

Upvotes: 1

Related Questions