Reputation: 747
I have this Array of Objects that I would need to transform into a flat Array of Objects. It looks as follows.
const points = [
{
highlights: [
{
title: 'Title 1',
description: 'Description 1',
x: 111,
y: 222,
},
{
title: 'Title 2',
description: 'Description 2',
x: 111,
y: 222,
},
],
width: 1108,
height: 1528,
relativePath: '/image_01.jpg',
},
{
highlights: [
{
title: 'Title 3',
description: 'Description 3',
x: 199,
y: 411,
},
{
title: 'Title 4',
description: 'Description 4',
x: 213,
y: 1132,
},
],
width: 1108,
height: 1528,
relativePath: '/image_02.jpg',
},
];
I would like each points.highlights[x] to have its own index so the Array would look as such:
[
{
title: 'Title 1',
description: 'Description 1',
x: 111,
y: 222,
width: 1108,
height: 1528,
relativePath: '/image_01.jpg',
},
{
title: 'Title 2',
description: 'Description 2',
x: 111,
y: 222,
width: 1108,
height: 1528,
relativePath: '/image_01.jpg',
},
{
title: 'Title 3',
description: 'Description 3',
x: 111,
y: 222,
width: 1108,
height: 1528,
relativePath: '/image_02.jpg',
},
{
title: 'Title 4',
description: 'Description 4',
x: 111,
y: 222,
width: 1108,
height: 1528,
relativePath: '/image_02.jpg',
},
];
I believe flatMap
is part of the solution but then I am unsure how exactly I would be able to retain the other properties (width
, height
, relativePath
).
I appreciate the help!
Upvotes: 1
Views: 97
Reputation: 368
Here's a solution using flatMap:
points.flatMap(point =>
point.highlights.flatMap(obj => {
let temp = { ... point, ... obj };
delete temp["highlights"];
return temp;
})
);
Upvotes: 1
Reputation: 22310
simply:
const points =
[ { highlights:
[ { title: 'Title 1', description: 'Description 1', x: 111, y: 222 }
, { title: 'Title 2', description: 'Description 2', x: 111, y: 222 }
]
, width : 1108
, height : 1528
, relativePath : '/image_01.jpg'
}
, { highlights:
[ { title: 'Title 3', description: 'Description 3', x: 199, y: 411 }
, { title: 'Title 4', description: 'Description 4', x: 213, y: 1132 }
]
, width : 1108
, height : 1528
, relativePath : '/image_02.jpg'
}
]
const result = points.reduce((res,{highlights,...plus})=>
{
highlights.forEach(hl=> res.push({...hl,...plus}))
return res
}
,[])
console.log(result)
Upvotes: 1