试图弄清楚为什么该功能不起作用

时间:2019-10-14 15:45:50

标签: javascript

我已经编写了一个过滤器函数,该函数应该过滤objets数组,并且确实对其进行过滤,但是结果变量不会得到过滤后的数组。

数组示例:

hotels: [{
  photo: "/some_address/some_photo.png",
  name: "Hotel Moscow Name",
  address: "Moscow, some street, 1",
  amenities: [{
      name: 'wi-fi'
    }, {
      name: 'bar'
    }, {
      name: 'pool'
    }, {
      name: 'transfer'
    },
    {
      name: 'bath'
    }, {
      name: 'breakfast'
    }, {
      name: 'spa'
    }
  ],
  price: 3000
},
{
  photo: "/some_address/some_photo.png",
  name: "Hotel  St.Pitersberg Name",
  address: "sSt.Pitersberg, some street, 2",
  amenities: [{
      name: 'wi-fi'
    }, {
      name: 'bar'
    }, {
      name: 'fitness'
    }, {
      name: 'transfer'
    },
    {
      name: 'bath'
    }, {
      name: 'breakfast'
    }, {
      name: 'spa'
    }
  ],
  price: 4000
},
}]
changeFilterValue: function(choosenAmenity) {
    this.changeFiltersList(choosenAmenity);
    let settedList = this.settedFilters;

    this.filteredData = this.hotels.filter(function(hotel) { //массив hotels
      let amenityArray = [];
      hotel.amenities.forEach(function(amenity) {
        amenityArray.push(amenity.name);
      })
      return settedList.filter(function(elem) {
        console.log(settedList, amenityArray);
        console.log(amenityArray.includes(elem));
        return amenityArray.includes(elem);
      });
    })
    console.log(this.filteredData);

1 个答案:

答案 0 :(得分:1)

settedList.filter(...)返回某个数组,该数组始终为truthy。如果要检查数组是否为空,请尝试使用return settedList.filter(...).length