0

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.

CodingBrah
  • 59
  • 8

2 Answers2

1

You should get your work done using findIndex() instead of your forEach.

This method would search and return the index of your condition, if is not found it will return -1

let result =  data.filter(product => product.inventoryItem.inventoryLevels.edges.findIndex(item => item.node.location.name !== "Warehouse Blue") !== -1 )
Rubén Vega
  • 722
  • 6
  • 11
0
 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?