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!
2 Answers 2
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)
answered Jun 11, 2021 at 13:57
Mister Jojo
23k6 gold badges28 silver badges45 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
suuuriam
Thanks, much appreciated!
Here's a solution using flatMap:
points.flatMap(point =>
point.highlights.flatMap(obj => {
let temp = { ... point, ... obj };
delete temp["highlights"];
return temp;
})
);
answered Jun 11, 2021 at 13:43
drrkmcfrrk
3783 silver badges15 bronze badges
1 Comment
suuuriam
Thanks, for your answer - unfortunately, I can't access lodash for this.
lang-js