I have a nested array, but I need to make a flat array from this array, but so that everything goes one by one
const data = [
{
titles: [
{
id: 1,
name: "Title 01",
subtitles: [
{
id: 2,
name: "Subtitle 01",
title_id: 1,
content: [
{
id: 3,
name: "Content 01",
subtitle_id: 2,
},
],
},
],
},
{
id: 4,
name: "Title 01",
subtitles: [
{
id: 5,
name: "Subtitle 01",
title_id: 4,
content: [
{
id: 6,
name: "Content 01",
subtitle_id: 5,
},
],
},
],
},
],
},
]
Need
const flatArr = [
{
titles01: {
name: "Title 01",
id: 1,
},
sutitles01: {
name: "Subtitle 01",
id: 2,
title_id: 1,
},
content01: {
id: 3,
name: "Content 01",
subtitle_id: 2,
},
titles02: {
name: "Title 02",
id: 4,
},
sutitles02: {
name: "Subtitle 02",
id: 5,
title_id: 4,
},
content02: {
id: 6,
name: "Content 02",
subtitle_id: 5,
},
},
]
That is, so that the array is flat and everything goes one by one, start with title01, then subtitle01, then content01, then title02, then sibtitle02, then content02, so that there is such a hierarchy, is this even possible? Unfortunately, I don’t have any code examples because nothing worked…
2
Answers
Here is the solution:
Here is a function that can give you desired result as above
const transformArray = (data) => {
return data.reduce((result, topLevelItem, index) => {
}, {});
};