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.