Skip to content Skip to sidebar Skip to footer

Traverse Through Multi-dimentional Object

I have a multi-dimensional object: var obj = { prop: { myVal: 'blah', otherVal: { // lots of other properties }, }, }; How would one t

Solution 1:

Recursion:

functiondoSomethingWithAValue(obj, callback) {
  Object.keys(obj).forEach(function(key) {
    var val = obj[key];
    if (typeof val !== 'object') {
      callback(val);
    } else {
      doSomethingWithAValue(val, callback);
    }
  });
}

Solution 2:

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}
<scriptsrc="https://bundle.run/object-scan@13.8.0"></script>

Disclaimer: I'm the author of object-scan

Post a Comment for "Traverse Through Multi-dimentional Object"