Convert a string to a nested JavaScript object or JSON

Viewed 435

I have the following string:

let str = "modules.mas.mas-helper-provider.assets.locales";

and would like to convert it to a nested JavaScript object (JSON), something like this result:

{
  "modules": {
    "mas": {
      "mas-helper-provider": {
        "assets": {
          "locales": ""
        }
      }
    }
  }
}
1 Answers

You can split the string to an array, then reduceRight to create an object by reading each key.

let str = "modules.mas.mas-helper-provider.assets.locales";

var newObject = str.split(".").reduceRight((obj, next) => ({
  [next]: obj
}), "");

console.log(newObject);

Related