I have an array of objects called dogs, each object has a key called type with a string value and a key called images with an array of objects. I want to flatten the array and copy the type key to each object in images array. I've managed to achieve this which produces the following result:
[
{
"type": "labrador",
"src": "unique-url"
},
{
"type": "labrador",
"src": "unique-url"
},
{
"type": "labrador",
"src": "unique-url"
},
{
"type": "german-shepherd",
"src": "unique-url"
},
{
"type": "german-shepherd",
"src": "unique-url"
},
{
"type": "german-shepherd",
"src": "unique-url"
},
{
"type": "husky",
"src": "unique-url"
},
{
"type": "husky",
"src": "unique-url"
},
{
"type": "husky",
"src": "unique-url"
}
]
However, I want to maintain the order of the initial array so it looks something like:
[
{
"type": "labrador",
"src": "unique-url"
},
{
"type": "german-shepherd",
"src": "unique-url"
},
{
"type": "husky",
"src": "unique-url"
},
{
"type": "labrador",
"src": "unique-url"
},
{
"type": "german-shepherd",
"src": "unique-url"
},
{
"type": "husky",
"src": "unique-url"
},
{
"type": "labrador",
"src": "unique-url"
},
{
"type": "german-shepherd",
"src": "unique-url"
},
{
"type": "husky",
"src": "unique-url"
}
]
How do I go about this? Any pointers would be greatly appreciated
const dogs = [
{
type: 'labrador',
images: [
{ src: 'unique-url'},
{ src: 'unique-url'},
{ src: 'unique-url'}
]
},
{
type: 'german-shepherd',
images: [
{ src: 'unique-url'},
{ src: 'unique-url'},
{ src: 'unique-url'}
]
},
{
type: 'husky',
images: [
{ src: 'unique-url'},
{ src: 'unique-url'},
{ src: 'unique-url'}
]
},
]
const result = dogs
.map((d) =>
d.images.map((i) => ({
type: d.type,
...i,
}))
)
.flat()
console.log(result)