Filter an array of objects that include a nested array

Currently, I am attempting to implement a nested filter on an array of objects. The challenge lies in applying the filter within the object based on a key that contains another array of objects.

Below is the snippet of code:

const items = [
  { name: "123", id: 1, value:  true, arr: [{ id: 1 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 2 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 3 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 4 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 5 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 6 }] },
];

const newArray = items.filter((objects) => {
  return objects.arr.some((item) => item.id === 2);
});
console.log(newArray);

I am unsure about where to place the return statement as my current implementation seems to only result in an empty array being returned.

Answer №1

Make sure to validate that the nested array includes the desired id and pass the outcome back to the filter method.

const
    items = [{ name: "123", id: 1, value: true, arr: [{ id: 1 }] }, { name: "456", id: 2, value: false, arr: [{ id: 2 }] }, { name: "456", id: 2, value: false, arr: [{ id: 3 }] }, { name: "456", id: 2, value: false, arr: [{ id: 4 }] }, { name: "456", id: 2, value: false, arr: [{ id: 5 }] }, { name: "456", id: 2, value: false, arr: [{ id: 6 }] }],
    result = items.filter(({ arr }) => arr.some(({ id }) => id === 2));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Utilize Array#some function to verify if the current array arr contains an element with an id of 2:

const items = [ { name: "123", id: 1, value:  true, arr: [{ id: 1 }] }, { name: "456", id: 2, value: false, arr: [{ id: 2 }] }, { name: "456", id: 2, value: false, arr: [{ id: 3 }] }, { name: "456", id: 2, value: false, arr: [{ id: 4 }] }, { name: "456", id: 2, value: false, arr: [{ id: 5 }] }, { name: "456", id: 2, value: false, arr: [{ id: 6 }] } ];

const newArray = items.filter(({ arr = [] }) => 
  arr.some(({ id }) => id === 2)
);

console.log(newArray);

Answer №3

Since there is only one object in the arr array, you can simply access it using the index [0].

Here's a Demo of How It Works:

const items = [
  { name: "123", id: 1, value:  true, arr: [{ id: 1 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 2 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 3 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 4 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 5 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 6 }] },
];

const newArray = items.filter((obj) => {
    if (obj.arr[0].id === 2) {
    return obj;
  }
});

console.log(newArray);

I provided this solution based on the specific issue you are facing. However, if there are multiple objects in your arr array, you might want to consider using the Array.some() method as recommended by other responses.

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

What are the differences between a Chrome app and extension? Is there any other way to access the tabs currently open in your

I need to develop an app that can access the tabs a user has open, but I'm struggling to find a way to do so without having my app run in Chrome itself. Creating an extension restricts the UI significantly, which is problematic since my app requires a ...

Retrieving values from multiple Select components in Material-UI is key

I have encountered an issue with my two MUI Select components on the page. I am attempting to set values based on the id of the Select component. Initially, when I check (id === "breed-select") in the console, it returns true, but shortly after ...

Missing data problem arises in convertHtml issue

Has anyone experienced data loss when converting HTML to PDF? I'm facing a problem with it. $scope.current.clause_note = '<ul><li>This is for testing <strong>TINTERIOR WORKS</strong></li></ul><p><br&g ...

Reorganize array structures by merging multiple arrays of objects in PHP

My issue involves merging and restructuring multiple arrays of objects imported from MySQL as JSON-encoded data. I aim to combine the [time] and [day] entries into an array of [cycle] so they can be looped over. After importing/decoding, each MySQL query&a ...

Recursive approach: Calculating the occurrence of a specific digit in a given numeric input: the encore

Earlier today, I brought up a similar question about identifying a specific digit within a number that was scanned in as text. My research led me to methods for finding the frequency of all digits, but none incorporating user input. While I grasp the conce ...

Challenges arise when attempting to transmit a list of JavaScript objects to a controller within a Spring MVC

I'm facing an issue with retrieving a list of JavaScript objects in Java Spring MVC - the list arrives empty in the controller. Despite reading extensively about it, I'm still struggling to understand how it works. Here is the AJAX code I am us ...

What is the best way to deduct pixels from numbers using JavaScript?

Currently, I am attempting to adjust the height of the footer based on the height of another div element. My approach involves utilizing the .css("height") function. However, I am encountering difficulty as the function does not seem to return the value i ...

Search for elements with a specific substring in their class names using the querySelectorAll() method

I'm working with a custom component in app.js return ( {cards.map((index) => { return <Card key={index} /> ) Within the Card component, I assigned a specific className return ( <ListItem id="root" className="find-card"&g ...

Create a JavaScript function to generate a random number every few seconds

Is there a way to quickly generate a fresh random number every second using the Math.random() method? I attempted placing it within a function and returning Math.random, but it keeps generating the same number. Are there any concise approaches to accompl ...

Node.js encountered an error due to a self-signed certificate within the certificate chain

I'm encountering an issue with client-side HTTPS requests. An example snippet is as follows: var fs = require('fs'); var https = require('https'); var options = { hostname: 'example.com', port: 443, path: & ...

Eliminate incorrect or invalid state when resetting a dropdown in an Angular ng-select component

I have integrated the ng-select plugin into my Angular project for handling dropdowns. One specific requirement I have is to reset the second dropdown when the first dropdown is changed. Below is a snippet of the code: <ng-select [items]="branchMo ...

Using NodeJS to integrate WebRTC into JavaScript applications

I am facing a challenge with my JavaScript files that I need to use for creating a WebRTC application. Unfortunately, my hosting platform does not support Node.js. I'm wondering if it's possible to modify these JS files to work without Node.js. C ...

Leverage jQuery to automatically submit an ajax form once all ajax requests have been successfully executed

I have integrated a WordPress plugin for store locator on my website. For pages without the interactive map, I have set up a form that serves as a location search tool. To clarify, the form includes a location field where users can input their desired loc ...

Encountering OAuthCallbackError while using Next.js Auth

I am currently working on developing an app for analyzing Spotify data. However, I am encountering an error related to authorization. Below is the content of my auth file: Here is the code snippet: import NextAuth from "next-auth"; import Spotif ...

I'm still undecided on what script I should use

I am striving to achieve a specific outcome, which can be found at this link http://farm8.staticflickr.com/7291/11250276724_fc1f751dc0_o.png. This image represents the desired end result. Regrettably, I am uncertain of the script required to accomplish t ...

Discover the parent DOM element of a specified element using jQuery

When using jQuery, I am currently exploring methods to navigate through the DOM until it locates a specific selector. For instance: Consider this structure: <span data-type="contact" data-filter="4" id="buyer-lookup" class="uneditable-input contact-lo ...

Saving a JavaScript array as a Redis list: A step-by-step guide

I'm trying to figure out how to save array values individually in a Redis list instead of saving the whole array as a single value. Any suggestions on how to achieve this? P.S. Please excuse my poor English. var redis = require('redis'), ...

Guide on incorporating d3 axis labels within <a> elements?

Issue at Hand: I am working with a specific scale var y = d3.scalePoint().domain(['a','b','c']).range([0,100]); I have successfully created an axis for this scale var y_axis = svg.append("g").attr("class", "axis").call(d3. ...

Utilizing PHP to dynamically load HTML forms and leveraging JQuery for form submissions

I am currently facing a dilemma that I am unsure how to approach. It seems that JQuery requires unique ID's in order to be called in the document ready function. I use PHP to read my MySQL table and print out HTML forms, each with a button that adds a ...

How can I properly set up the view in Backbonejs?

Whenever I try to initialize my view, I encounter an error message Uncaught TypeError: Cannot read property 'toJSON' of undefined Here is the code snippet causing the issue: //Model var Song = Backbone.Model.extend({ defaults: { ...