I have a nested array of objects:
const nestArray = [
{
title: "title 1",
children: [
{
title: "title 1-1",
children: [
{ title: "title 1-1-1", children: [...] },
{ title: "title 1-1-2", children: [...] }
]
},
{
title: "title 1-2",
children: [
{ title: "title 1-2-1", children: [...] },
{ title: "title 1-2-2", children: [...] }
]
},
]
},
{...},
{...}
]
All objects have the same interface:
interface Obj {
title: string
children: Obj[]
}
I need to put a new key into each object called keys.
The keys will keep all its children's titles alongside its own title. So the final result should be:
const nestArray = [
{
title: "title 1",
keys: ["title 1", "title 1-1", "title 1-1-1", "title 1-1-2"],
children: [
{
title: "title 1-1",
keys: ["title 1-1", "title 1-1-1", "title 1-1-2"],
children: [
{ title: "title 1-1-1", keys: ["title 1-1-1"], children: [] },
{ title: "title 1-1-2", keys: ["title 1-1-2"], children: [] }
]
},
{
title: "title 1-2",
keys: ["title 1-2", "title 1-2-1", "title 1-2-2"],
children: [
{ title: "title 1-2-1", keys: ["title 1-2-1"], children: [] },
{ title: "title 1-2-2", keys: ["title 1-2-2"], children: [] }
]
},
]
},
{...},
{...}
]
so the interface will be changed as:
interface Obj {
title: string
children: Obj[]
keys: string[]
}
I searched a lot but couldn't find any solution on the internet. I tried to solve this problem on my own, using recursive functions but still, I couldn't do it.
Using lodash is fine
What i've tried so far:
const mapTitlesToKeys = (obj) => {
obj.keys = [obj.title];
obj.children.forEach((childObj) => {
mapTitlesToKeys(childObj);
obj.keys.push(childObj.title);
});
};
nestArray.forEach((obj) => {
mapTitlesToKeys(obj);
});
console.log(nestArray);
results in:
[
{
title: "title 1",
keys: ['title 1', 'title 1-1', 'title 1-2'], // <-- should be ["title 1", "title 1-1", "title 1-1-1", "title 1-1-2"]
children: [
{
title: "title 1-1",
keys: ['title 1-1', 'title 1-1-1', 'title 1-1-2'], // <-- should be ["title 1-1", "title 1-1-1", "title 1-1-2"]
children: [
{
title: "title 1-1-1",
keys: ["title 1-1-1"], // <-- fine
children: []
},
{
title: "title 1-1-2",
keys: ["title 1-1-2"], // <-- fine
children: []
}
]
},
{
title: "title 1-2",
keys: ['title 1-2', 'title 1-2-1', 'title 1-2-2'], // <-- should be ["title 1-2", "title 1-2-1", "title 1-2-2"]
children: [
{
title: "title 1-2-1",
keys: ["title 1-2-1"], // <-- fine
children: []
},
{
title: "title 1-2-2",
keys: ["title 1-2-2"], // <-- fine
children: []
}
]
},
]
},
{...},
{...}
]
title: "title 1"they keys need to include the items from both1-1and1-2--> in the above question, right?