【问题标题】:JS: Filter() Array of Objects based on nested array in object?JS:Filter()对象数组基于对象中的嵌套数组?
【发布时间】:2021-07-17 08:32:25
【问题描述】:

数据

const data = [
  {
    id: 1,
    title: "Product Red",
    inventoryItem: {
      inventoryLevels: {
        edges: [{ node: { location: { name: "Warehouse Red" } } }],
      },
    },
  },
  {
    id: 2,
    title: "Product Blue",
    inventoryItem: {
      inventoryLevels: {
        edges: [{ node: { location: { name: "Warehouse Blue" } } }],
      },
    },
  },
];

  let result = data.filter((product) => {
    return product.inventoryItem.inventoryLevels.edges.forEach((inventoryLevel) => {
      return inventoryLevel.node.location.name !== "Warehouse Blue";
    });
  });

  console.log(result);

我想要做的是按位置名称过滤。我不知道如何构建基于嵌套数组的过滤。

所以我想要的结果是位置不是 Warehouse Blue。数据应该只有位置名称为仓库红色的对象。

【问题讨论】:

    标签: javascript arrays filter


    【解决方案1】:

    您应该使用 findIndex() 而不是 forEach 来完成工作。

    这个方法会搜索并返回你的条件的索引,如果没有找到它会返回-1

    let result =  data.filter(product => product.inventoryItem.inventoryLevels.edges.findIndex(item => item.node.location.name !== "Warehouse Blue") !== -1 )
    

    【讨论】:

      【解决方案2】:
       let result = data.filter((product) => {
          return product?.inventoryItem?.inventoryLevels?.edges
          .some(edge => edge?.node?.location?.name !== ('Warehouse Blue'))
      });
      

      也可以使用lodash Lodash: how do I use filter when I have nested Object?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-15
        • 1970-01-01
        • 2016-11-17
        • 1970-01-01
        • 1970-01-01
        • 2021-08-22
        • 1970-01-01
        • 2014-09-13
        相关资源
        最近更新 更多