gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:24:07 25 4
gpt4 key购买 nike

目前我有以下对象数组

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com