{
"cities":[
{"name":"bangalore","hotels":["park","leela","mac"]},
{"name":"chennai","hotels":["shang","mang","bang"]},
{"name":"hyderabad","hotels":["taj","oberai","ibis"]}
]}
我一直在尝试cities.filter(“bangalore”),检索与班加罗尔相关的酒店,但我无法收到它
答案 0 :(得分:1)
您可以使用filter(obj => obj.name === 'bangalore')
获取名称为bangalore
的对象,如果名称可以为Bangalore
,则可以使用filter(obj => obj.name.toLowerCase() === 'bangalore')
。
var data = {
"cities":[
{"name":"bangalore","hotels":["park","leela","mac"]},
{"name":"chennai","hotels":["shang","mang","bang"]},
{"name":"hyderabad","hotels":["taj","oberai","ibis"]}
]};
var res = data.cities.filter(obj => obj.name === 'bangalore');
console.log(res);
您还可以使用forEach()
循环来获取与bangalore
var data = {
"cities":[
{"name":"Bangalore","hotels":["park","leela","mac"]},
{"name":"chennai","hotels":["shang","mang","bang"]},
{"name":"bangalore","hotels":["taj","oberai","ibis"]}
]};
var hotels = [];
data.cities.forEach((obj) => {
if(obj.name.toLowerCase() === 'bangalore'){
hotels.push(...obj.hotels);
}
});
console.log(hotels);