如何将过滤器应用于以下代码?

时间:2018-05-09 06:28:31

标签: arrays filter

{
"cities":[
    {"name":"bangalore","hotels":["park","leela","mac"]},
    {"name":"chennai","hotels":["shang","mang","bang"]},
    {"name":"hyderabad","hotels":["taj","oberai","ibis"]}
    ]}

我一直在尝试cities.filter(“bangalore”),检索与班加罗尔相关的酒店,但我无法收到它

1 个答案:

答案 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);