Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping nested arrays using map in es6

I am trying to loop through nested arrays using map.

const results = [
{
    id: 1,
    details: [
        {
            color: "red",
        }
    ]
},
{
    id: 2,
    details: [
        {
            color: "blue",
        }
    ]
}]

const list1 = results.map(car => { 
   return car.details;
})

const list2 = list.map(details => {
   return {
     detail: details.color
} 
});

console.log(list1);
console.log(list2);

List1 is displaying fine:

​​​​​[ [ { color: 'red' } ], [ { color: 'blue' } ] ]​​​​​

However with list2 I am getting the following:

[ { detail: undefined }, { detail: undefined } ]​​​​​

Could anyone help me to map through the nested array?

like image 536
Jim Dover Avatar asked Mar 29 '26 17:03

Jim Dover


1 Answers

Try following

const results = [
{
    id: 1,
    details: [
        {
            color: "red",
        }
    ]
},
{
    id: 2,
    details: [
        {
            color: "blue",
        }
    ]
}]

const list1 = results.map(car => { 
   return car.details;
});

// assuming there was a typo here it should be list1
const list2 = list1.map(details => { 
   return {
     detail: details[0].color // details is an array
   } 
});

console.log(list1);
console.log(list2);
like image 140
Nikhil Aggarwal Avatar answered Mar 31 '26 07:03

Nikhil Aggarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!