3

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?

2 Answers 2

7

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, exactly what I was wanting!
@Pedro no worries, .flatMap() is a new feature to JS so it isn't supported by all browsers at the moment. I've added a version using .reduce() which has better browser support
0

Rather than having a nested map (resulting in a 2D return value), you could declare a new array and only push the values you'd like. This results in a 1D array.

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

const results = [];

data.forEach(d => {
  d.yards.forEach(y => {
    results.push({
      start: d.due_at,
      end: d.due_at,
      title: y.name
    });
  });
});

console.log(results);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.