简体   繁体   中英

How to check if value exists in a nested array/object

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM