简体   繁体   English

如何检查嵌套数组/对象中是否存在值

[英]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)?我 go 如何检查颜色“黑色”是否存在(如果有多个动物以及有关它们的所有信息,这也将起作用)?

Iterate through the info.animals property array.遍历info.animals属性数组。 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.也许 some 或 every 对你也有用或有趣,它只返回 boolean。如果至少有一只或什至没有一只动物有黑色,有些给出 true 或 false。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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