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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With