Home > Back-end >  How to check if value exists in a nested array/object
How to check if value exists in a nested array/object

Time:09-29

If I have a data structure like

let info = {
  animals: [
    {
      number: 1,
      name: 'Zebra',
      colour: 'Black',
      code: '233'
    }
  ],
}

How would I go about checking if the colour 'Black' exists (which will also work if there is multiple animals and all the information about them)?

CodePudding user response:

Iterate through the info.animals property array. Check for the conditions you want.

const info = {
  animals: [
    {
      number: 1,
      name: 'Zebra',
      colour: 'Black',
      code: '233'
    }
  ],
}

const list = info.animals;

list.forEach(i => {
  if (i.colour === 'Black') {
     // do something
     console.log(true);
  }
});

CodePudding user response:

I think the most interesting of the following three options is filter. According to your question, you also want all the information about the animals which are black. So, the result of filter is a new array only consisting of the objects (animals) with black color.

Maybe some or every is also useful or interesting for you, which only return a boolean. Some gives true or false if at least one or not even one animal has black colour. Every gives true/false if all/not all animals have black colour.

let info = {
  animals: [
    {
      number: 1,
      name: 'Zebra',
      colour: 'Black',
      code: '233'
    }
  ],
}

// Returns all objects (animals) which have black colour
const filter = info.animals.filter((obj)=> obj.colour === 'Black')

// Returns true only if any or false if no animal has black colour
const some = info.animals.some((obj)=> obj.colour === 'Black')

// Returns true only if all or false if not all animals (objects) have black colour
const every = info.animals.every((obj)=> obj.colour === 'Black')

console.log("FILTER: "   filter.length   " animal(s) with black color. These are: ", filter )
console.log("SOME: "   "At least one black animal? ", some)
console.log("EVERY: "   "Every animal in array has black colour? ",every)

  • Related