遍历多维对象 [英] Traverse through multi-dimentional 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?
SO上还有两个与该主题相关的其他问题:
There are a couple other questions on SO that are related to the topic:
遍历Javascript对象属性
javascript遍历对象
问题在于两个答案都不完全是我想要的,因为:
The problem is that both answers are not quite what I am looking for, because:
a):第一个链接仅遍历对象的第一层.
b)第二个答案要求您知道对象键的名称.
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.
推荐答案
递归:
function doSomethingWithAValue(obj, callback) {
Object.keys(obj).forEach(function(key) {
var val = obj[key];
if (typeof val !== 'object') {
callback(val);
} else {
doSomethingWithAValue(val, callback);
}
});
}
这篇关于遍历多维对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文