Looking at this JavaScript object
var items = [{
content: 'A_lvl0',
}, {
content: 'B_lvl0',
}, {
content: 'C_lvl0',
children: [{
content: 'C_1_lvl1',
}, {
content: 'C_2_lvl1',
children: [{
content: 'C_1_lvl2'
}, {
content: 'C_2_lvl2',
children:[{
content: 'C_1_lvl3'
}, {
content: 'C_2_lvl3'
}]
}]
}, {
content: 'C_3_lvl1'
}]
}];
The "lvlx" in the content property of each object indicates how deeply nested it is. If we need to determine the nesting level of a specific object within this structure using recursion, we might encounter challenges in keeping track of the top level.
We have a function that can print out all nested contents of objects:
var scanObj = function (obj) {
for (var i = 0; i < obj.length; i++) {
console.log(obj[i].content);
if (obj[i].hasOwnProperty('children')) {
scanObj(obj[i].children);
}
}
};
Now we are trying to create functions like:
var getlvlByRef = function (obj,subobject) {
//return lvl
};
var getlvlByPropertyValue = function (obj,propertyname,propertyvalue) {
//return lvl
};
The challenge lies in determining the correct approach to keep track of the depth when reaching the innermost nested levels. Any guidance on this would be greatly appreciated.
You can also check out the code snippet on this fiddle http://jsfiddle.net/eG3qR/