I have the following nested array which I to preserve and keep the same, but also attach a property called indexes to each nested items object which stores a top-down list of indexes so I can keep track of the nested items when I flatten the array and use it elsewhere in my app. The structure looks like this:
[
{
cat: '1'
items: [
{
media: [
{
type: 'image'
}
]
},
{
media: [
{
type: 'image'
}
]
},
{
media: [
{
type: 'image'
}
]
}
]
},
{
cat: '2',
items: [
{
media: [
{
type: 'image'
},
{
type: 'image'
}
]
}
]
},
{
cat: '3',
items: [
{
media: [
{
type: 'image'
}
]
}
]
}
];
And I'd like it to look like the following, where indexes starts at 0 for the first item, and for each occurrence within the media array attaches an incrementing number and binds it as a property.
[
{
cat: '1',
items: [
{
indexes: [0],
media: [
{
type: 'image'
}
]
},
{
indexes: [1],
media: [
{
type: 'image'
}
]
},
{
indexes: [2],
media: [
{
type: 'image'
}
]
}
]
},
{
cat: '2',
items: [
{
indexes: [3, 4],
media: [
{
type: 'image'
},
{
type: 'image'
}
]
}
]
},
{
cat: '3',
items: [
{
indexes: [5],
media: [
{
type: 'image'
}
]
}
]
}
];
What is the best way to do this?
In my opinion the most elegant way would be to run through all the items using a forEach loop.
const cats = [{
cat: '1',
items: [{
media: [{
type: 'image'
}]
},
{
media: [{
type: 'image'
}]
},
{
media: [{
type: 'image'
}]
}
]
},
{
cat: '2',
items: [{
media: [{
type: 'image'
},
{
type: 'image'
}
]
}]
},
{
cat: '3',
items: [{
media: [{
type: 'image'
}]
}]
}
];
let totalIndex = 0
cats.forEach(cat => {
cat.items.forEach(item => {
item.indexes = item.media.map(() => totalIndex++)
})
})
console.log(cats)