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
  • 30,841
  • 27
  • 92
  • 100
Gabriel Petrovay
  • 20,476
  • 22
  • 97
  • 168

0 Answers0