+ 6

Need help with JavaScript recursive nested objects & arrays

I am trying to create a function to access values within a reoccurring object nested within arrays of itself. For example: // Recursive nested objects & arrays var obj = { children: [ { parentname: "level 0", children: [{ parentname: "level 0.0", children: [{ parentname: "level 0.0.0", children: [] }, { parentname: "level 0.0.1", children: [{ parentname: "level 0.0.1.0", children: [] }] }] }, { parentname: "level 0.1", children: [] }] }, { parentname: "level 1", children: [] }] }; // Able to retrieve values with various length formulas console.log(obj.children[0].parentname); // level 0 console.log(obj.children[0].children[0].parentname); // level 0.0 console.log(obj.children[0].children[0].children[0].parentname); // level 0.0.0 console.log(obj.children[0].children[0].children[1].parentname); // level 0.0.1 console.log(obj.children[0].children[0].children[1].children[0].parentname); // level 0.0.1.0 console.log(obj.children[0].children[1].parentname); // level 0.1 console.log(obj.children[1].parentname); // level 1 // Able to reduce formulas into functions...per level of nesting, example 1 level function getNameWorking1(name, level) { console.log(obj[name][level].parentname); } getNameWorking1(["children"], [1]) // Able to reduce formulas into functions...per level of nesting, example 2 levels function getNameWorking2(name, level) { console.log(obj[name][level[0]][name][level[1]].parentname); } getNameWorking2(["children"], [[0], [0]]) // Trying to create 1 function, that I can send a parameter with the length needed to get results. function getNameNotWorking(parameter) { console.log(parameter) console.log(obj[parameter].parentname); } getNameNotWorking("[children][1]"); getNameNotWorking("[children][0][children][1]"); This last function is not working. Any help on how to do this?

25th Feb 2019, 6:21 PM
Wubba Lubba Dub Dub
Wubba Lubba Dub Dub - avatar
1 Antwort
+ 3
I found the answer I was looking for as shown at https://code.sololearn.com/WD9U3qvuzxVC/#html
25th Feb 2019, 6:34 PM
Wubba Lubba Dub Dub
Wubba Lubba Dub Dub - avatar