I have the following scenario: I have an array of objects (TreeItems) which could contain nested arrays. And I have another Array with indexes. Now I would like to change the TreeItems array using the indexes array to access a specific tree item and depending on if there is a nested array called "items" I would like to either append the existing one or add a new one. And mostly important, I would like to get rid of the evil eval.
So in my example I try to add a new entry at TreeItems[4][0][0] but the indexes in the brackets should be added dynamically from the indexes array but I'm not quite shure how to do this.
I have searched of course and found this one, but it doesn't quite work for me.
Any help would be greatly appreciated.
const TreeItems = [
{ text: "Lvl 0", items: [{ text: "Lvl 0-0" }, { text: "Lvl 0-1" }] },
{ text: "Lvl 1" },
{ text: "Lvl 2", items: [{ text: "Lvl 2-0" }, { text: "Lvl 2-1" }] },
{ text: "Lvl 3" },
{
text: "Lvl 4",
items: [
{
text: "Lvl 4-0",
items: [
{
text: "Lvl 4-0-0",
items: [{ text: "Lvl 4-0-0-0" }, { text: "Lvl 4-0-0-1" }, { text: "Lvl 4-0-0-2" }],
},
{ text: "Lvl 4-0-1" },
{ text: "Lvl 4-0-2" },
],
},
],
},
];
const indexes = [4,0,0];
let comString = '';
for(let i = 0; i < indexes.length; i++) {
if(i === 0) {
comString = "TreeItems[" + indexes[i] + "]";
} else {
comString += ".items[" + indexes[i] + "]";
}
}
if(eval(comString).items !== undefined) {
eval(comString).items.push({"text": "Test-item-appended"});
} else {
eval(comString).items = [{"text": "Test-items-added"}]
}
console.log(comString);
console.log(eval(comString).items);
console.log(TreeItems);