Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 574
Peace Pan Avatar asked May 09 '26 09:05

Peace Pan


1 Answers

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);
like image 65
Pranav C Balan Avatar answered May 10 '26 23:05

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!