简体   繁体   中英

Traverse through multi-dimentional object

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.

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);
    }
  });
}

Consider using object-scan . It's powerful for data processing once you wrap your head around it. Here is how you'd do a simple iteration in delete safe order:

 // const objectScan = require('object-scan'); const obj = { prop: { myVal: 'blah', otherVal: { /* lots of other properties */ } } }; objectScan(['**'], { filterFn: ({ key, value }) => { console.log(key, value); } })(obj); // => [ 'prop', 'otherVal' ] {} // => [ 'prop', 'myVal' ] blah // => [ 'prop' ] { myVal: 'blah', otherVal: {} }
 .as-console-wrapper {max-height: 100% !important; top: 0}
 <script src="https://bundle.run/object-scan@13.8.0"></script>

Disclaimer : I'm the author of object-scan

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM