Itsik Mauyhas Itsik Mauyhas - 2 months ago 6
Javascript Question

Find and retrive object value by key, include nested objects

I am trying to find a

value
by
key
without knowing the object, include nested object, so the function will get a key and a object and return the value or undefined.
This is my function:

/* Iterate over object and include sub objects */

function iterate (obj, key) {

for (var property in obj) {
if (obj.hasOwnProperty(property)) {
//in case it is an object
if (typeof obj[property] == "object") {
if (obj.hasOwnProperty(key)) {
return obj[key]; //return the value
}
}
else {
iterate(obj[property]);
}
}
}

return undefined;
}


I call
return
inside a loop so it will be more efficient(hope so...).

1.is anyone have this function ready? this one does not work.

2.someone knows what to change to make it work?

Any help, including
angular.js
functions will be great.

Thanks.

Answer

You reversed things a bit and you forgot to pass the second parameter to the recursive function call. Also, in this case there's no need to return undefined, because that is the default.

function iterate (obj, key) {
    for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
            //in case it is an object
            if (typeof obj[property] === "object") {
                return iterate(obj[property], key);
            }
            else {
                return obj[key]; //returns the value 
            }
        }   
    }
}