2

I am trying to convert a flat object in dot notation (like MongoDb uses for the updates) into a hierarchical one.

The input object for example is:

var flat = {
    "a": 123,
    "b.c": "234",
    "b.d.e": 345
}

The current conversion code is:

var obj = {};
var parent = obj;
Object.keys(flat).forEach(function(key) {
    var subkeys = key.split('.');
    var last = subkeys.pop();
    subkeys.forEach(function(subkey) {
        parent[subkey] = typeof parent[subkey] === 'undefined' ? {} : parent[subkey];
        parent = parent[subkey];
    });
    parent[last] = flat[key];
    parent = obj;
});

Is there a better way (JS trick) to do it?

Machavity
  • 29,816
  • 26
  • 86
  • 96
Gabriel Petrovay
  • 18,575
  • 19
  • 87
  • 153

0 Answers0