I've been trying to solve a problem with arrays and objects for some time now - but I still can't find the right solution.
This is my starting position:
list = [
{
lastItemData: {data:"root"},
path: ["Root"]
},
{
lastItemData: {data:"level2_Summer"},
path: ["Root", "Level2_Summer"]
},
{
lastItemData: {data:"Level3_Monday"},
path: ["Root", "Level2_Winter", "Level3_Monday"]
},
{
lastItemData: {data:"Level4_Morning"},
path: ["Root", "Level2_Spring", "Level3_Tuesday", "Level4_Morning"]
},
{
lastItemData: {data:"Level3_Sunday"},
path: ["Root", "Level2_Autumn", "Level3_Sunday"]
}]
and this is what i need:
result = [
{
text: "Root",
lastItemData: {data:"root"},
Items:[
{
text:"Level2_Summer",
lastItemData: {data:"level2_Summer"},
Items: []
},
{
text:"Level2_Winter",
Items:[
{
text: "Level3_Monday",
lastItemData: {data:"Level3_Monday"},
Items: []
}
]
},
{
text:"Level2_Spring",
Items:[
{
text: "Level3_Tuesday"
Items: [
{
text:"Level4_Morning"
Items:[],
lastItemData: {data:"Level4_Morning"},
}
]
}
]
},
{
text:"Level2_Autumn",
Items:[
{
text: "Level3_Sunday"
}
]
},
]
}]
I'v try something like this (code is based on user jonas answer from my deleted post)
const property = list.reduce((previous, current, index) => {
let acc = {}; //the accumulator that will go deep into the object
const result = acc; //our result will be the top level object
debugger;
//Now we iterate over our array
for (var i = 0; i < current.stringPath.length; i++) {
debugger;
//add the string part
acc["level" + (i + 1)] = current.stringPath[i];
//Add the children array
acc["Items"] = [{}];
//And go into the object
acc = acc["Items"][0];
}
console.log(result)
previous.push(result);
return previous;
}, []);
console.log("property", property);
But unfortunately the result does not correspond to the desired structure. Can anyone help me?