Peace Pan Peace Pan - 2 months ago 17
Javascript Question

Javascript, how to split key with dot to recovery json structure

I have a json, it is

{
"prop1.sub1.sub2": "content1",
"prop1.sub1.sub3": "content2",
"prop2.sub1.sub2": "content3",
"prop3.sub1.sub2": "content4"
}


I want to recovery the structure, like

{
"prop1": {
"sub1": {
"sub2" : "content1",
"sub3" : "content2"
}
},
"prop2": {
"sub1": {
"sub2" : "content3"
}
},
"prop3": {
"sub1": {
"sub2" : "content4"
}
}
}


I split the key with dot to get each key.

for (var key in json) {
var keySplit = key.split('.');
// Todo: recovery the structure
}


But not found a good solution.

Is anyone has solution?

Answer

You can use Array#reduce method.

var obj = {
  "prop1.sub1.sub2": "content1",
  "prop1.sub1.sub3": "content2",
  "prop2.sub1.sub2": "content3",
  "prop3.sub1.sub2": "content4"
};

// iterate over the property names
Object.keys(obj).forEach(function(k) {
  // slip the property value based on `.`
  var prop = k.split('.');
  // get the last value fom array
  var last = prop.pop();
  // iterate over the remaining array value 
  // and define the object if not already defined
  prop.reduce(function(o, key) {
    // define the object if not defined and return
    return o[key] = o[key] || {};
    // set initial value as object
    // and set the property value
  }, obj)[last] = obj[k];
  // delete the original property from object
  delete obj[k];
});

console.log(obj);