Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS nested array.map

Hi I have the following data:

data = [{due_at: '2019-09-10', yards:[{name: 'test'},{name: 'test2'}]}...]

I am wanting to iterate over this date to result in:

events = [{start: '2019-09-10', end: '2019-09-10, title: 'test'},{start: '2019-09-10', end: '2019-09-10, title: 'test2'}...]

I have tried using the following nested map:

events = data.map(d => {
    return d.yards.map(y => {
      return {
        start: d.due_at,
        end: d.due_at,
        title: y.name
      };
    });
  });

Which works to a point but I keep getting back a nested array like so:

[[{start: '2019-09-10', end: '2019-09-10, title: 'test'},{start: '2019-09-10', end: '2019-09-10, title: 'test2'}...]]

How can I adjust my map code to output a single array of objects?

like image 953
Pedro Avatar asked Apr 07 '26 00:04

Pedro


1 Answers

You could use .flatMap() instead of .map() on your outer-map function to "flatten" the contents into your resulting array from your inner map function:

const data = [{
  due_at: '2019-09-10',
  yards: [{
    name: 'test'
  }, {
    name: 'test2'
  }]
}];

const events = data.flatMap(d => {
  return d.yards.map(y => {
    return {
      start: d.due_at,
      end: d.due_at,
      title: y.name
    };
  });
});

console.log(events);

However, .flatMap() doesn't have the best browser support at the moment, so, if you're after something a little more browser compatible, you can use .reduce() instead of .flatMap():

const data = [{
  due_at: '2019-09-10',
  yards: [{
    name: 'test'
  }, {
    name: 'test2'
  }]
}];

const events = data.reduce((a, {due_at: start, yards}) => 
  [...a, ...yards.map(({name:title}) => ({start, end: start, title}))],
[]);

console.log(events);
like image 171
Nick Parsons Avatar answered Apr 08 '26 14:04

Nick Parsons



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!