Answer the question
In order to leave comments, you need to log in
Why doesn't the recursion stop?
There is a JS object of unknown nesting. That is, inside it, among other properties, there are more objects, and in them, in turn, there are more objects, etc. It looks something like this:
var trunk = {
listItem1: 1,
listItem2: {
subListItem: 1,
subListItem2: {
subsubListItem1: 1,
subsubListItem2: 2
}
},
listItem3: 3
}
function search(obj) {
for (var key in obj) {
if (obj[key] == "1") {
console.log(key + '>')
} else if (typeof obj[key] == "object") {
console.log(this + '>');
return search(this);
} else {
// "I dont need this"
}
}
};
Answer the question
In order to leave comments, you need to log in
return search(this) ?
you are calling the function with the current context. And you need to call with the object in which you want to search, i.e. obj[key]. Well, return is certainly not needed. Because otherwise you will exit the loop after the first hit on the object.
I took the liberty of adding a second argument (to increase the string indicating the path to the property)
if you don't mind, then you can do something like this
const trunk = {
listItem1: 1,
listItem2: {
subListItem: 1,
subListItem2: {
subsubListItem1: 1,
subsubListItem2: 2
}
},
listItem3: 3
};
const ones = [];
traverse(trunk, 'root');
function traverse(obj, path) {
for(let key in obj) {
const newPath = path + ' > ' + key;
if (obj[key].constructor.name === "Object") {
// console.log(newPath);
return traverse(obj[key], newPath);
}
if(obj[key] == "1") {
ones.push(newPath);
}
}
console.log('properties\' pathes which value is equal to 1 \n\n' , ones);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question