javascript - 在对象的子数组中搜索 - JavaScript

标签 javascript arrays loops object search

目前我有以下对象数组

obj = [
    {
        "id":28,
        cities: [
            {
                cityTypes: "AA",
                citySource: "sdsf"
            },
            {
                cityTypes: "BB",
                citySource: "sdsgf"
            },
            {
                cityTypes: "CC",
                citySource: "fgsdfgd"
            }
        ]
    }, 
    {
        "id":56,
        cities: [
            {
                cityTypes: "DD",
                citySource: "sdsf"
            },
            {
                cityTypes: "EE",
                citySource: "sdsgf"
            },
            {
                cityTypes: "FF",
                citySource: "fgsdfgd"
            }
        ]
    }, 
    {
        "id":89,
        cities: [
            {
                cityTypes: "GG",
                citySource: "sdsf"
            },
            {
                cityTypes: "HH",
                citySource: "sdsgf"
            },
            {
                cityTypes: "II",
                citySource: "fgsdfgd"
            }
        ]
    }
]

我需要搜索 cityTypes 的特定值存在于整个 Object 中。

假设,我需要搜索 cityTypes = BB

如果BB存在于整个对象中,返回true

如果BB没有被预设,返回false

这个是我试过的,好像不行。

for(let k=0; k<obj.length; k++){
    if(obj[k].cities){
        let cityObj = obj[k].cities;
        for(let city in cityObj){
            city.cityTypes !== "BB" ? "true" : "false"
        }
    }
}

实现这一目标的正确方法是什么?

最佳答案

您可以在另一个 .some 中使用 .some:

const obj=[{"id":28,cities:[{cityTypes:"AA",citySource:"sdsf"},{cityTypes:"BB",citySource:"sdsgf"},{cityTypes:"CC",citySource:"fgsdfgd"}]},{"id":56,cities:[{cityTypes:"DD",citySource:"sdsf"},{cityTypes:"EE",citySource:"sdsgf"},{cityTypes:"FF",citySource:"fgsdfgd"}]},{"id":89,cities:[{cityTypes:"GG",citySource:"sdsf"},{cityTypes:"HH",citySource:"sdsgf"},{cityTypes:"II",citySource:"fgsdfgd"}]}];

console.log(
  obj.some(({ cities }) => cities.some(({ cityTypes }) => cityTypes === 'BB'))
);
console.log(
  obj.some(({ cities }) => cities.some(({ cityTypes }) => cityTypes === 'foobar'))
);

关于javascript - 在对象的子数组中搜索 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52217029/

相关文章:

java - 从文本文件中读取二维数组

使用循环打印 PHP 数组

javascript - Chrome 开发者工具本地修改损坏

javascript - javascript中的谷歌地图infoWindow(通过循环创建多个infoWindow)

javascript - jQuery 音频 : How to Allow Overlapping Sounds?

c# - 将嵌入式资源读入字节数组时出错 (C#)

c# - 如何在锯齿状数组中查找唯一值

python - 检测循环中的最后一次迭代

java - 将数组中的对象元素添加到字符串数组中

javascript - 不知道为什么这个函数返回一个反转的数组