简体   繁体   English

JS:Filter() 基于对象中嵌套数组的对象数组?

[英]JS: Filter() Array of Objects based on nested array in object?

The data数据

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

What I want to do is filter by location name.我想要做的是按位置名称过滤。 I am not sure how to construct filtering based on nested arrays.我不确定如何基于嵌套数组构建过滤。

So the result I want is if the location isn't Warehouse Blue.所以我想要的结果是位置不是蓝色仓库。 data should just have the object where location name is warehouse red.数据应该只有位置名称为仓库红色的对象。

You should get your work done using findIndex() instead of your forEach.您应该使用 findIndex() 而不是 forEach 来完成您的工作。

This method would search and return the index of your condition, if is not found it will return -1此方法将搜索并返回您的条件的索引,如果未找到它将返回 -1

let result =  data.filter(product => product.inventoryItem.inventoryLevels.edges.findIndex(item => item.node.location.name !== "Warehouse Blue") !== -1 )
 let result = data.filter((product) => {
    return product?.inventoryItem?.inventoryLevels?.edges
    .some(edge => edge?.node?.location?.name !== ('Warehouse Blue'))
});

Can use lodash too Lodash: how do I use filter when I have nested Object?也可以使用 lodash Lodash:当我嵌套对象时如何使用过滤器?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM