Searching through a nested array to find and retrieve the sub-array that contains the specified value for a given key

I have a scenario where I need to filter out specific arrays of objects from an array based on their id values. However, the current solution is returning an empty array when there is no match for the filter condition.

Any suggestions on how to resolve this issue?

const resKey = 'ABC';
const data = [
  [{
    "user": {
      "firstName": "John",
      "lastName": "Smith",
    },
    "id": "ABC"
  }],
  [{
    "user": {
      "firstName": "John",
      "lastName": "Smith",
    },
    "id": "DEF"
  }]
];

const result = data.map(eachArr => eachArr.filter(eachObj => eachObj.id === resKey));
console.log(result);

Desired Output:

[
  [
    {
      user: {
        firstName: "John",
        lastName: "Smith",
      },
      id: "ABC",
    },
  ],
]

Current Output:

[
  [
    {
      user: {
        firstName: "John",
        lastName: "Smith",
      },
      id: "ABC",
    },
  ],
  [],
]

Answer №1

To eliminate the empty arrays that do not contain any elements (where length is 0), you can utilize the filter method.

.filter((arr) => arr.length);

const resKey = "ABC";
const data = [
  [
    {
      user: {
        firstName: "John",
        lastName: "Smith",
      },
      id: "ABC",
    },
  ],
  [
    {
      user: {
        firstName: "John",
        lastName: "Smith",
      },
      id: "DEF",
    },
  ],
];

const result = data
  .map((eachArr) => eachArr.filter((eachObj) => eachObj.id === resKey))
  .filter((arr) => arr.length);
  
console.log(result);

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 is the best way to access a field from a different table within a loopback environment

In my Loopback setup, I have two models named Permissions and langs_translate that I am working with in a loop. Here are the structure of the tables: Permissions: -------------------------- | id | icon | link | -------------------------- | 1 | da ...

Is there a way to determine in Python whether the numbers within an array are all identical?

Is it possible to check for symmetry in an array without knowing its length? For instance, determining if the first and last elements are equal, followed by the second and second-to-last, and so on. This is particularly challenging as the data is randoml ...

PHP - Sorting Two Arrays in Sync

I have two arrays that contain information about people. One array, named a, includes the names of different individuals, while the other array, named b, includes their ages. I successfully sorted array b in descending order based on age. Now, I need to f ...

Learn how to send dynamic data to another HTML element using Ajax's success function

I received a successful ajax response from one HTML file, but I'm struggling to dynamically set the data from this response to another HTML file. Can anyone help me with this issue? Here is the code snippet from my ajax report: success: function( ...

How to Add Motion to Several Markers

Exploring the concept of moving markers on a map with drawn polylines to simulate simultaneous movement is a fascinating challenge. However, encountering some difficulties, such as only the last marker moving while the others remain stationary, can be frus ...

Transform js into a more dynamic format to avoid redundancy when displaying items upon click

I came across a simple lightbox code snippet, but it's based on IDs and I plan to use it for more than 20 items. I don't want to manually write out 20 JavaScript lines when there could be a more efficient way to handle it dynamically. My JS skill ...

Showing the default option at all times with React Material-UI Autocomplete

For my address search/verification form in React, I'm utilizing the Material-UI Autocomplete component and I want to always display a default option regardless of the search results. In Angular, I achieved this by using [displayWith] along with a fun ...

Working with numerous query parameters within AngularJS

When interfacing with an external service, I’m receiving query parameters in the following format: url/?error=someError&error_description=someErrorDescription In my app.js file, I have attempted to handle this using the routeProvider as shown below ...

Unavailable dates on Datepicker (information fetched from the database)

I am currently working on extracting dates from my database and storing them in an array as json data. In my MAIN.PHP file: $('#datepicker').focus(function(){ $.ajax({ url: 'getDates.p ...

Retrieve a comprehensive inventory of all routes within a Vue project and automatically create a sitemap for the website - Vue Project

Imagine I've set up a route like this: import Vue from "vue"; import Router from " vue-router"; import BookRoutes from "./routes/book"; Vue.use(Router) const router = new Router({ routes:[ { path ...

What is the process for reloading the helper after modifying the values?

After the user selects an option, I am trying to filter information on my page. I created a "change" event and passed values through sessions. The console log shows that the values are being passed correctly. However, it seems like the helper is not refres ...

Using JavaScript or Node.js, learn how to update links with a common header file

I need help updating links on my website for different pages. My website has a common header file with a navbar that includes a dropdown menu for selecting languages. Currently, I am using the same header file for all pages. When a language is selected fr ...

fetching json information using jquery's .get method

<script> $.get("url", function(data, textStatus, jqXHR) { var jsonData = JSON.stringify(data); }); // I want to use the **jsonData** variable here </script> Hi there, I'm trying to fetch some data from a specific URL. ...

An issue has arisen where Jasmine, when operating on Grunt, is unable to locate

It seems that the async functions (waits, waitsFor, runs) in Jasmine are not accessible when running it from Grunt. Grunt setup: jasmine:{ pivotal:{ src: 'src/**/*.js', options:{ specs: 'spec/**/*.spec.js&ap ...

Identifying the presence of a CSS class in order to add styling to a different element

Looking for help with CSS: /* targeting laptops */ @media only screen and (pointer:fine) and (max-device-height: 620px) { #root:has(.projects) ~ body { overflow: auto; /* allow scrolling */ } } My desired outcome is to set overflow: auto o ...

Trigger an "onMouseMove" event when the "pointer-events-none" css property is applied to fire

Currently, I am dealing with a React Component that contains an absolutely positioned div overlaying other content within my application. This particular div is utilized to trigger react's onMouseMove event. My objective is to apply the CSS value poi ...

Steps to dynamically set the value of an input type="time" using JavaScript

Despite the repetitive nature of these questions, I have yet to find a solution to my specific query. Any help would be greatly appreciated. Thank you in advance. The HTML code is as follows: var start="10:30 PM"; $scope.edit={} frtime=start.split("PM ...

What is the process of including data in Vue using refs?

My goal is to click a button and have the page scroll up or down. However, I need references for each span I add in order to include an index. The issue arises when trying to incorporate this index into the method. How can I add data to these references? ...

How do you update the icon for a webpage in HTML?

I'm looking to update the icon on a button when it is clicked. It would be helpful to know if I can also add an animation to the icon after the button click. ...

Challenges with custom select boxes in Firefox

Is anyone else experiencing issues with a custom select box in Firefox? It seems like the problem might be related to the code snippet below: $(".custom-select-trigger").on("click", function() { $('html').one('click',function() { ...