How to use the filter() method to filter an array of objects based on a nested array within each object

The following data presents a list of products along with their inventory information:

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

I am looking to filter this data based on the location names. I am unsure how to handle nested arrays for filtering.

Therefore, my desired outcome is to have the object in the 'data' array where the location name is not 'Warehouse Blue', resulting in only the entry with the location name 'Warehouse Red' remaining.

Answer №1

Consider utilizing findIndex() instead of forEach to complete your tasks efficiently.

With this approach, findIndex() will locate and provide the index of your specified condition; if not found, it will return -1.

Opt for using findIndex() over forEach for improved productivity:

Answer №2

 const filteredProducts = data.filter((item) => {
    return item?.inventoryItem?.inventoryLevels?.edges
    .some(edge => edge?.node?.location?.name !== ('Warehouse Blue'))
});

For a different approach, you can also utilize lodash as shown in this Stack Overflow thread about using filter with nested objects.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue when transmitting information from Angular to Express

I'm attempting to send data from Angular to Express.js Below is my TypeScript function connected to the button: upload(): void { const nameFromId = document.getElementById('taskName') as HTMLInputElement; this.taskName = nameFromI ...

Utilize Google Drive and scripts to incorporate map images into a React application

I'm currently working on setting up an album feature on my react website for a friend, and I would like the images in the album to be linked to a Google Drive so that he can easily upload new images whenever he wants. After successfully inserting the ...

ReferenceError: _jquery2.default.ajax is not a function" encountered in a React Native application

I have been attempting to use jQuery to retrieve xml data from an internal website. My expo project setup is quite basic and resembles the following: import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; imp ...

Jest is simulating a third-party library, yet it is persistently attempting to reach

Here's a function I have: export type SendMessageParameters = { chatInstance?: ChatSession, // ... other parameters ... }; const sendMessageFunction = async ({ chatInstance, // ... other parameters ... }: SendMessageParameters): Promise<vo ...

PHP - Store an implementation of an interface within an array

Having trouble finding the answer online, I'm not quite sure how php and interfaces work. The issue is with the if(!variable instanceof class) statement. The checked class is actually an interface and needs to be in an array, as shown in the followin ...

Javascript Developer Platform glitches

Describing this issue is proving difficult, and I have been unable to find any solutions online. My knowledge of Javascript and its technologies is still quite new. I am currently working on a web application using NodeJS, Express, and Jade that was assig ...

Tips for expanding button width in 'react-native-swipeout' to enable swipe action on ListView row (React Native)

Currently, I am exploring how to implement the component found here: https://github.com/dancormier/react-native-swipeout My goal is to have the row swiped all the way. Is there a method to increase the button width so that it covers the entire width of th ...

Can the values in all fields of a JSON be combined or subtracted with those of another object containing the same fields?

I am currently working with a Mongoose.js schema that is structured as follows: { "City": String, "Year": String, "Population": Number, "Blah": Number, "Nested": { "Something": Number, "More stuff": Number } } Is there an efficient w ...

Pressing the submit button will not successfully forward the form

I've encountered an issue with my submit buttons - when I click on them, nothing happens. They were functioning properly before, but now they seem to be unresponsive. What could be causing this problem? <form id="contact" name="updateorder" acti ...

Django Vue3 encounters access-control-allow-origin restriction

I am currently working on a Django rest-api project that uses Vue on the front-end. Unfortunately, I encountered an error while making requests via Vue: Console output: The following error is displayed: Access to XMLHttpRequest at 'https://api.iyziw ...

Is it necessary to specify the server-side script within the "routes" directory?

I'm currently developing a NodeJS Express application and from what I gather, the communication between the server and client is achieved by incorporating an AJAX script in a JavaScript file (on the client-side) and implementing a listener function (f ...

Condition in SQL for searching full name with no specific order of first name or last name

How can I search for a column named fullname by filtering on firstname/lastname without specific order? In the following Javascript example, the query is invalid when searching by lastname: function getQuery(searchWord){ return `SELECT * FROM user WHERE ...

Guide to integrating jssor into an AngularJS application

Struggling to integrate jssor with angularjs, it seems to be failing because jssor is being initialized before angularjs, causing the ng-repeat elements to not resolve correctly. <div id="slider1_container"> <div u="slides"> <!-- Th ...

AngularJS Module Instantiation Error

My angularjs module is not loading correctly and I'm struggling to figure out why. Despite reading numerous tutorials, I can't seem to get it to work. [17:22:36.338] Error: [$injector:modulerr] Failed to instantiate module wc2013mongoMod due t ...

JavaScript: table is not defined

When creating a table using Django models and JavaScript, I encountered an issue where the cells values of the table could not be accessed from another JavaScript function. The error message indicated that the table was "undefined". Below is the HTML code ...

Enter data into the appropriate columns

Within my Angular 6 application, I am creating a table with the following structure: Html: <table> <thead> <tr> <th> Property Details &nbsp; &nbsp; &nbsp; &nbsp; ...

Is there a way to convert a URL into a user-friendly json format displayed on a web page

Can someone please help me figure out the proper way to convert this URL into a JSON format that is easily readable using jQuery on an HTML page? ...

Reverting a concealed segment

Can anyone make sense of my unconventional explanation? I've set up a hidden section as shown below: <section class="intro"> <label> <input type="checkbox"> <span class="menu"> <span class="hamburger"></span&g ...

Having trouble altering the error response code in feathers.js

I'm utilizing an authentication service for login validation. In this case, I am looking to change the Unauthorized (401) response code to 200 while keeping the message the same. The authentication service setup is as follows: app.service('auth ...

Is it truly possible to return a reactive variable that updates its value asynchronously?

While reviewing the code of a frontend project developed in Vue3, I came across a unique construction that I have not encountered before. This has led to some confusion as I try to grasp how it operates. The concept involves assigning the result of an asyn ...