Navigating through two nested arrays in JavaScript to access an object

Having difficulty extracting the nested car values using JavaScript (lodash). Take a look at the JSON data below:

{
 "cars":[
   {
      "nestedCars":[
         {
           "car":"Truck",
           "color":"Red",
           "type":"Honda"
        }
     ]
  },
  {
     "nestedCars":[
        {
           "car":"Sedan",
           "color":"Blue",
           "type":"Ford"
           
        }
     ]
   }

   ]
 }

The JSON response is retrieving the data correctly.

 this.carLevels = response.data.cars;

The code snippet below is returning all data when only expecting two cars (Truck and Sedan).

 carData() {   
   result = _.filter(this.carLevels, "nestedCars[0].car")
       }

Tried using nested functions as well but with no success.

  result = this.carLevels.filter(function (a) {
    return a.nestedCars.some(function (b) {
        return b.car;
     });
  });

Not sure what I'm doing incorrectly here.

Essentially, trying to retrieve all car items from the JSON data.

Expected output:
car:"Truck" car:"Sedan"

Answer №1

If you utilize Array#flatMap on the main array, you can then map out the car property from the nested arrays.

const
    data = { cars: [{ nestedCars: [{ car: "Truck", color: "Red", type: "Honda" }] }, { nestedCars: [{ car: "Sedan", color: "Blue", type: "Ford" }] }] },
    cars = data.cars.flatMap(({ nestedCars }) => nestedCars.map(({ car }) => ({ car })));

console.log(cars);

Answer №2

Using lodash is no longer necessary for this type of operation as native array methods have significantly improved.

(Please note: I made slight modifications to your input data to illustrate how the scenario would change if nestedCars contained more than one element. If each object in response.data.cars consistently has only one entry, you could simplify the data structure without losing any information.)

response = {
  data: {
    "cars": [{
        "nestedCars": [{
            "car": "Truck",
            "color": "Red",
            "type": "Honda"
          },
          {
            "car": "Jeep",
            "color": "Yellow",
            "type": "Jeep"
          }
        ]
      },
      {
        "nestedCars": [{
          "car": "Sedan",
          "color": "Blue",
          "type": "Ford"
        }]
      }
    ]
  }
}

this.carLevels = response.data.cars;

// ---- 

carList = this.carLevels.flatMap(el => { // iterate over data.cars
  return el.nestedCars.map(item => { // iterate over each nestedCars
    return item.car // extract the "car" value
  })
})

console.log({car: carList})

Answer №3

Another efficient alternative to flatMap() is using Array::reduce() as it doesn't involve creating intermediate arrays. This is particularly advantageous in Chrome, where flatMap() is 6.2 times slower due to the use of iterators compared to regular array loops.

const
    data = { cars: [{ nestedCars: [{ car: "Truck", color: "Red", type: "Honda" }] }, { nestedCars: [{ car: "Sedan", color: "Blue", type: "Ford" }] }] },
    cars = data.cars.reduce((r, { nestedCars }) => (nestedCars.forEach(({ car }) => r.push({ car })), r), []);

console.log(cars);

` Chrome/118
-----------------------------------------------------------
Alexander      1.00x  |  x10000000  160  162  163  166  169
Nina Scholz   15.25x  |   x1000000  244  248  248  250  253
-----------------------------------------------------------
https://github.com/silentmantra/benchmark `
` Firefox/119
----------------------------------------------------------
Alexander     1.00x  |  x10000000  553  583  588  595  607
Nina Scholz   1.65x  |   x1000000   91   93  106  107  114
----------------------------------------------------------
https://github.com/silentmantra/benchmark `

const data = { cars: [{ nestedCars: [{ car: "Truck", color: "Red", type: "Honda" }] }, { nestedCars: [{ car: "Sedan", color: "Blue", type: "Ford" }] }];

// @benchmark Nina Scholz
data.cars.flatMap(({ nestedCars }) => nestedCars.map(({ car }) => ({ car })));

// @benchmark Alexander
data.cars.reduce((r, { nestedCars }) => (nestedCars.forEach(({ car }) => r.push({ car })), r), []);

/*@end*/eval(atob('e2xldCBlPWRvY3VtZW50LmJvZHkucXVlcnlTZWxlY3Rvcigic2NyaXB0Iik7aWYoIWUubWF0Y2hlcygiW2JlbmNobWFya10iKSl7bGV0IHQ9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7dC5zcmM9Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9naC9zaWxlbnRtYW50cmEvYmVuY2htYXJrL2xvYWRlci5qcyIsdC5kZWZlcj0hMCxkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHQpfX0='));

Answer №4

Using flatMap in this situation is the solution:

let allVehicles = response.data.vehicles.flatMap(
    vehicle => vehicle.nestedVehicles.map(
        item => item.vehicle))

In essence, if you are looking to simply "retrieve" elements, map or flatMap are the way to go, not filter or some.

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

Custom Sign-in features in NextJS now direct users to the default form for entering login

I have been working on a web app that requires authentication using NextJS default auth middleware. However, whenever I try to log in, the app redirects me to the default NextJS form component at the URL /api/auth/signin?error=CredentialsSignin. Even thou ...

Watch mp4 clips in various languages with ExpressJs

I have a question regarding streaming videos within my local network. My mp4 files contain multiple audio tracks in different languages. Is there a way to select a specific audio track to stream? For instance, could you specify a language as a query parame ...

Obtaining the jqXHR object from a script request loaded within the <head> tag using the <script> tag

Is it possible to retrieve the jqXHR object when a script loaded from a script tag within the head tag? function loadScript(url){ const script = document.createElement("script"); script.src = url; // This line will load the script in the ...

Modifying Element Values with JavaScript in Selenium using C#

As a newcomer to automation, I am facing a challenge with automating a web page that has a text field. I initially attempted using driver.FindElement(By.XPath("Xpath of elemnt").SendKeys("Value"); but unfortunately, this method did not work. I then resor ...

Unable to implement str.replace function within HTML code

Within my Angular app, I'm looking to replace all instances of _ within a string. In my controller, the following code achieves the desired outcome: alert("this_is_string_".replace(/_/g, " ")); However, when attempting to implement the same code wit ...

Serialize custom objects with an array of custom objects using Spring Boot and JSON

Let's take a look at this interesting class structure: @Id @GeneratedValue(strategy=GenerationType.AUTO) private long id; private int key; private String text; private Tag[] tags; private String title; private boolean valid; public Activity(int key, ...

Undefined TypeScript Interface

Here's my situation: public retrieveConnections() : IUser[] { let connections: IUser[]; connections[0].Id = "test"; connections[0].Email = "asdasd"; return connections; } I know this might be a dumb question, but why is connecti ...

Updating or removing fullCalendar events in Symfony

I'm struggling to figure out how to update or delete fullcalendar events in my Symfony project. When adding a new event, I open a modal window with a form for submitting the event and inserting it into the database. This is my working controller: $ ...

Using Retrofit2 to display JSON data in a RecyclerView

I've been trying to use Retrofit2 to fetch JSON data and then parse it into my RecyclerView adapter without much success. Currently, I can populate one RecyclerView with local DBFlow data, but I'm struggling to do the same for the JSON data retri ...

Having trouble with Vue component registration repeatedly failing

Currently, I am working on a front-end project using [THIS VUE TEMPLATE][https://www.creative-tim.com/product/vue-material-dashboard-pro] The issue I am facing involves trying to register a component locally and encountering the following error: "1 ...

Upon loading, make sure to click on the link located within the third <li> tag

I am working with a list (<ul>): <ul class="options_inner"> <li><a data-dk-dropdown-value=".option1"></a></li> <li><a data-dk-dropdown-value=".option2"></a></li> <li><a data- ...

Issue with fullPage.js - Unable to scroll to footer on the last section of the page

I'm currently working with the fullPage.js plugin () and encountering some issues. While sliding through each section, everything functions as expected. However, when I reach the last section and try to scroll down to the footer below it, I encounter ...

How can you retrieve the original file name and line number in exceptions that are generated in Angular controllers?

When an error occurs in my Angular controller, a stack trace is generated that typically looks like the following: TypeError: undefined is not a function at new <anonymous> (…/dist/script.js:854:5) at invoke (…/dist/base-script.js:13441: ...

Unable to organize list of entities based on numerical values

I am working with an array of objects structured like this: [ { "value": 351.68474, "o_p": [ "$.text" ] }, { "value": 348.0095, "o_p": [ ...

Crafting JSON using the jq tool

I need help creating a JSON file using jq from the output of the "lsb_release" command. This is what I've tried: if [ -x "$(command -v lsb_release)" ]; then lsb_release -a | jq --raw-input 'split("\t") | { (. [0]) : . [1] }' > ...

The Checkbox handler in Material-UI component fails to update the state - Version 5.0

Hey everyone, I'm facing an issue with my "Checkbox" component in React. After clicking on it, the state doesn't update to 'true' as expected. The checkbox works visually in the DOM but the state remains 'false'. Can someone p ...

The output of the http.get or http.request callback is only visible within the shell when using node.js

Just dipping my toes into node and aiming to avoid falling into the callback hell trap. I'm currently working with two files: routes.js fetch.js //routes.js var fetchController = require("../lib/mtl_fetcher/fetcher_controller"); var express = requir ...

What is the best way to extract information from a JSON array using Gson?

Currently, I have obtained a json file with data structured in the following format: [ [ "name1", "age1", "gender1", url1 ], [ "name2", "age2", "gender2", url2 ], ... ] I am looking to parse this data and s ...

What is the method for altering the color of specific columns?

I am currently testing out my Amchart with this example. Check out the working demo on code pen My goal is to modify the color of the first four columns. While I am aware that colors can be changed by specifying them in the JSON file as a property calle ...

Elevating the Material Design Lite Progress bar using ReactJS

I currently have MDL running with React and it appears to be functioning properly. The Progress Bar is displaying on the page as expected, loading with the specified progress on page load when a number is entered directly: document.querySelector('#qu ...