问题
I have a multi-dimensional object:
var obj = {
prop: {
myVal: "blah",
otherVal: {
// lots of other properties
},
},
};
How would one traverse the entire object, without knowing any of the property names or the number of "dimensions" in the object?
There are a couple other questions on SO that are related to the topic:
Traverse through Javascript object properties
javascript traversing through an object
The problem is that both answers are not quite what I am looking for, because:
a) The first link only iterates through the first layer in the object.
b) The second answer requires you to know the names of the object's keys.
回答1:
Recursion:
function doSomethingWithAValue(obj, callback) {
Object.keys(obj).forEach(function(key) {
var val = obj[key];
if (typeof val !== 'object') {
callback(val);
} else {
doSomethingWithAValue(val, callback);
}
});
}
来源:https://stackoverflow.com/questions/35662068/traverse-through-multi-dimentional-object