如何通过第二个嵌套数组过滤具有嵌套数组的对象?

时间:2018-12-21 15:07:44

标签: javascript arrays angularjs typescript

我有一个具有如下结构的对象。

Object{
    Array [{
        property1: "",
        property2: "",
        innerArray: [{
            arrayProperty1
            arrayProperty2
          }]
    }]
}

通过innerArray.Property2进行过滤的最佳方式是什么?我有一个需要应用的过滤器列表。下面的代码是我当前尝试应用过滤器的方式,但是列表根本没有改变。

    if(filterList)
    {
      // if this length is 0, don't include inventory in the filter
      let filterOnInventoryId = filterList.filter((item: any) => {
        return (item && item.Type === 'InventoryId');
      });


      let shouldFilterInventoryId = filterOnInventoryId && filterOnInventoryId.length > 0;
      let shouldFilterAppointmentType = filterOnAppointmentType && filterOnAppointmentType.length > 0;

      // find any inventoryIds that are part of the filter, else return an empty list
      let filteredListInventoryId = shouldFilterInventoryId ? filterOnInventoryId.filter((item: any) => 
      {
        var x = this.selectedDateAndAppointmentList.filter((dateModelAndAppointment: any) => 
        {
          return dateModelAndAppointment.appointmentList.filter((appointment: any) =>{
            item.InventoryTypeId == appointment.Inventory.InventoryTypeId;
          })
        })
        return x;
      }) : [];

    }

1 个答案:

答案 0 :(得分:0)

嵌套数组过滤,例如:

npm install && npm shrinkwrap

不会对顶部数组进行任何过滤,因为selectedDateAndAppointmentList.filter(dateModelAndAppointment => dateModelAndAppointment.appointmentList.filter(...) ); 总是返回一个数组,因此您的代码正在根据Array.prototype.filter的真实性进行过滤,而该真实性始终是真实的,并且没有任何内容被过滤。

[]

这是正在发生的事情

selectedDateAndAppointmentList.filter(dateModelAndAppointment =>
  dateModelAndAppointment.appointmentList.filter(...)
  // ^ will always return true because appointmentList.filter always returns an array
);

相反,您应该使用// no filtering is happening because inner // filter always returns a truthy value console.log( [{ values: ["a", "b"] }, { values: ["c", "d"] }].filter(item => item.values.filter(val => val === "a") ) );Array.prototype.some,它们返回布尔值而不是数组,因此可以用作过滤条件:

Array.prototype.every

例如:

selectedDateAndAppointmentList.filter(dateModelAndAppointment => 
  dateModelAndAppointment.appointmentList.some(...)
  // ^ this will return a boolean based on a nested array condition
)