Traverse through multi-dimentional object

浪尽此生 提交于 2019-12-12 03:48:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!