How do i extract until the last sub_data into an array and also get the data from the third sub_data to form another structure?
[{
"id": 2,
"title": "Logo",
"sub_data": [
{
"id": 5,
"title": "Facebook",
"sub_data": [
{
"id": 6,
"title": "People",
"sub_data": [
{
"id": 7,
"title": "Gardening",
}
],
},
],
}]
Example output: category is from the title of the third sub_data
[{
title: 'Logo',
id: 2:
data: [{
id: 7,
title: 'Gardening'
category: 'People'
}]
}]
CodePudding user response:
const data =
[{
"id": 2,
"title": "Logo",
"sub_data": [
{
"id": 5,
"title": "Facebook",
"sub_data": [
{
"id": 6,
"title": "People",
"sub_data": [
{
"id": 7,
"title": "Gardening",
}
],
},
],
}
]
}]
let newArray = [];
let obj = {};
data.forEach(item1 => {
item1.sub_data.forEach(item2 => {
item2.sub_data.forEach(item3 => {
item3.sub_data.forEach(item4 => {
obj = {
title: item1.title,
id: item1.id,
data: [
{
id: item4.id,
title: item4.title,
category: item3.title
}
]
}
})
})
newArray.push(obj)
})
})
console.log(newArray)