1

I have a nested object which I don't know about nested level in this object and for now I want to convert all properties of it to paths like prop.prop[0].prop after that I should save all theme in an array.

nested_obj = {
  name: 'Saeid',
  images: [ { format: 'jpg', id: 23 }, { format: 'png', id: 30 }],
  ids: [ 2111, { id: [ 222, 'library'] } ]
}

paths_array = [ 'name', 'images[0].format', 'images[0].id', 'images[1].format', 'images[1].id' ]

How I can reach to this? I have a solution as below which didn't work for ids[1].id[0]

var make_path;

make_path = function(obj) {
  var Deep;
  Deep = function(o, paths, preKey) {
    var arrayKey, i, j, k, keys, l, len, ref, v;
    if (paths == null) {
      paths = [];
    }
    if (Array.isArray(o)) {
      for (i = j = 0, ref = o.length - 1; 0 <= ref ? j <= ref : j >= ref; i = 0 <= ref ? ++j : --j) {
        if (typeof o[i] !== 'object') {
          paths.push(preKey + "[" + i + "]");
          Deep(o[i], paths, preKey);
        } else {
          console.log(o[i]);
          arrayKey = preKey + "[" + i + "]";
          Deep(o[i], paths, arrayKey);
        }
      }
    } else if (o instanceof Object) {
      keys = Object.keys(o);
      for (v = l = 0, len = keys.length; l < len; v = ++l) {
        k = keys[v];
        if (typeof o[k] !== 'object') {
          if (preKey != null) {
            paths.push(preKey + "." + k);
          } else {
            paths.push(k);
          }
        }
        Deep(o[k], paths, k);
      }
    }
    return console.log(paths);
  };
  return Deep(obj);
};
Elfayer
  • 4,411
  • 9
  • 46
  • 76
SAlidadi
  • 85
  • 10
  • Have a look at [Fastest way to flatten / un-flatten nested JSON objects](http://stackoverflow.com/q/19098797/1048572) – Bergi Oct 18 '16 at 13:33

1 Answers1

0

I use the NPM library dot-object for this very often. It has a simple API and can be used to serialize and deserialize to dot strings. It can also be used in node apps or in the browser.

https://www.npmjs.com/package/dot-object

Keith Morris
  • 2,125
  • 1
  • 19
  • 21