I have the following data that is an array of nested objects:
let sections = [
{
name: "section1",
id: 1,
menus: [
{
id: 1,
name: "menu1"
},
{
id: 2,
name: "menu2"
}
]
},
{
name: "section2",
id: 2,
menus: [
{
id: 3,
name: "menu3"
},
{
id: 4,
name: "menu4"
}
]
}
]
I need an array of objects with properties from both nested objects. Expected Output:
[
{sectionId: 1, sectionName: "section1", menuId: 1, menuName: "menu1"},
{sectionId: 1, sectionName: "section1", menuId: 2, menuName: "menu2"},
{sectionId: 2, sectionName: "section2", menuId: 3, menuName: "menu3"},
{sectionId: 2, sectionName: "section2", menuId: 4, menuName: "menu4"}
]
Tried with below code:
let combined = sections.map(section => {
let menus = section.menus.map(menu => {
return{
menuId: menu.id,
menuName: menu.name,
sectionName: section.name,
sectionId: section.id
}
})
return menus
})
Actual Output:
[[{"menuId":1,"menuName":"menu1","sectionName":"section1","sectionId":1},{"menuId":2,"menuName":"menu2","sectionName":"section1","sectionId":1}],[{"menuId":3,"menuName":"menu3","sectionName":"section2","sectionId":2},{"menuId":4,"menuName":"menu4","sectionName":"section2","sectionId":2}]]
Getting Arrays of arrays of objects. Tried a lot using reduce and map but not getting the expected output. Any help is greatly appreciated.