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

Chronological Overview (Highcharts)

Can you customize a timeline in Highcharts to resemble the image? I have a functional example of the timeline I desire, but the color coding and filtering aspects are challenging for me. I am attempting to apply a filter that will decrease the opacity of ...

Discovering targeted information from object utilizing React

When using the fetch method to retrieve film data, how can I extract specific details from the returned object? I am able to access and manipulate properties like name, genre, cast, trailers, and recommendations, but I'm struggling with retrieving the ...

Issue in Angular form: Element removal from the DOM does not remove it at the specified index, instead removes the last item

I'm encountering an issue where the wrong element is being removed from the DOM. In my onDelete() method, I am deleting a specific FormControl at a certain index, but in the actual DOM, it's removing the last item instead of the intended one. Fo ...

Implement a function to trigger and refresh components in various Vuejs2 instances simultaneously

I currently have index.html with two Vue instances in different files: <!DOCTYPE html> <html lang="en"> <body> <div id="appOne"> </div> <div id="appTwo"> </div> </body> </html ...

Trouble Navigating the DOM

Can you assist me in choosing the correct option c? Below is the provided HTML code: <div id="a"> <div id="b"></div> <div id="app7019261521_the_coin_9996544" style="left: 176px; top: 448px;"> <a href="d.com" oncl ...

I have a vision of creating a unique Countdown Stopwatch that meets all my

I'm looking to create a custom countdown stopwatch where I can set the time and watch it count down to 0:00. The stopwatch should have three buttons: Start, Stop, and Reset. I've searched multiple websites for what I need but haven't found ...

Which is better for PHP Localization: gettext or array?

As I work on setting up my multi-language site, one key decision I need to make revolves around how to handle static text. To provide some context, my site is set up as a CMS system where multiple domains can point to the same directory and display content ...

Exploring an Array within a Function in Ruby

Hello, I am new to using Ruby. I'm currently working on a program that takes user input, compares it with numbers in an array, and if there's a match, adds it to another number passed to the function. Here's what I have so far: numbers = [1 ...

A Step-by-Step Guide to Setting Up and Utilizing V-Calendar in Vue.js

I am currently trying to incorporate the V-Calendar library into my Vuetify application. Up until now, the app was working fine, but I seem to have hit a roadblock with the correct installation of the V-Calendar library. Although no error messages are bei ...

What is the best way to automatically select a checkbox when using ng-repeat on page

I'm looking to automatically check an input checkbox when the page loads, and if it's checked, subtract its value from the total. How can I tackle this issue? Here's the HTML snippet: <p>{{vm.TOTAL VALUE}}</p> <tr ng-repeat= ...

How can I ensure that my script reruns when the window is resized?

Clearly, the question is quite straightforward... I have a script that is drawing graphics across the window. Currently, when I resize the window (e.g., make it full screen), the script only responds to the original size of the window. It should refresh a ...

Problem with autocomplete functionality in Angular Material's md-contact-chips

Having some trouble with the autocompletion feature of md-contact-chips. I want to capture the $query as soon as someone starts typing. HTML <md-contact-chips ng-model="members" md-contacts="querySearch($query)" md-contact-name="fullname" ...

Align Headers to the Top Center in React Material-UI Datagrid

Is there a way to align the wrapped headers at the top-center using sx? I've tried the following code: const datagridSx = { '& .MuiDataGrid-columnHeaders': { height: 'unset !important', maxHeight: '168p ...

Pop-up windows, the modern day digital version of fortune cookies

Expressing my requirement might be a bit challenging, but I will do my best. My goal is to create a web application using ASP.Net with C#. This project calls for functionality similar to the Windows popup: When a user clicks on the favorite button in IE- ...

Is there a JavaScript API available for conducting currency calculations?

I'm facing an arithmetic problem that requires handling decimal numbers in JavaScript. Is there an API available for performing comparison, subtraction, and addition of decimals that also supports locale/language-specific formatting? Any suggestions o ...

Storing and retrieving dictionary data using PHP without relying on JSON

Currently, I'm in the process of developing a search engine that requires storing multiple data against a single word. I need to implement this functionality using PHP without relying on JSON. I am also contemplating whether PHP is the best choice for ...

Using Play Scala reads to parse a JSON collection

Let's start with a hypothetical scenario where we have a case class: case class Element(name: String) and its companion object which includes a reads method: object Element { implicit val elementReads = ( (JsPath / "name").read[String] ) } ...

What is the best way to trigger an event using vue-chartjs?

I am using vue js to display a graph with chartjs. I have implemented an onClick function on the graph to emit an event in the parent component and retrieve data. However, the event is not working as expected. Can you help me identify the issue? Component ...

Switch button displaying stored data in sessionStorage

I am facing an issue with my small toggle button in AngularJS. I have set up sessionStorage to store a value (true or false), and upon page load, I retrieve this value from sessionStorage to display the toggle button accordingly. Depending on the value sto ...

Saving and retrieving user input as a variable using Javascript and HTML local storage

This is the foundation of my HTML page. When the "remember text" paragraph is clicked, the data in the input text box is saved to local storage as a string. Clicking the "recall text" paragraph loads the stored data into the "recalled text" paragraph. I am ...