问题
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.
回答1:
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) {
var result;
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
// in case it is an object
if (typeof obj[property] === "object") {
result = iterate(obj[property], key);
if (typeof result !== "undefined") {
return result;
}
}
else if (property === key) {
return obj[key]; // returns the value
}
}
}
}
EDIT: Actually, we should check if the property is equal to the key BEFORE checking if the value is an iterable object, in the case where we are looking for a key whose value is an object. Thanks to @Catinodeh!
function iterate (obj, key) {
var result;
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (property === key) {
return obj[key]; // returns the value
}
else if (typeof obj[property] === "object") {
// in case it is an object
result = iterate(obj[property], key);
if (typeof result !== "undefined") {
return result;
}
}
}
}
}
回答2:
Unflatten it first with the function that solved this problem: Fastest way to flatten / un-flatten nested JSON objects
and then simply use hasOwnProperty
again
来源:https://stackoverflow.com/questions/39596031/find-and-retrive-object-value-by-key-include-nested-objects