【问题标题】:How to filter an object that has nested arrays by the second nested array?如何通过第二个嵌套数组过滤具有嵌套数组的对象?
【发布时间】:2019-05-22 01:20:11
【问题描述】:

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

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;
      }) : [];

    }

【问题讨论】:

    标签: javascript arrays angularjs typescript


    【解决方案1】:

    嵌套数组过滤如:

    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.someArray.prototype.every,它们返回布尔值而不是数组,因此可以用作过滤条件:

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

    例如:

    // filtering now works because the inner filter
    // correctly returns a boolean value depending 
    // on the filter condition
    console.log(
      [{ values: ["a", "b"] }, { values: ["c", "d"] }].filter(item =>
        item.values.some(val => val === "a")
      )
    );

    【讨论】:

      猜你喜欢
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2020-03-11
      • 1970-01-01
      • 2020-03-08
      • 1970-01-01
      • 2021-11-21
      • 2020-07-18
      相关资源
      最近更新 更多