2

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": ""
        }
      }
    }
  }
}
hc_dev
  • 8,389
  • 1
  • 26
  • 38
Hani
  • 157
  • 2
  • 9
  • Also see: [Dot notation object to multi-dimensional object](https://stackoverflow.com/questions/67494499/dot-notation-object-to-multi-dimensional-object/67495055#67495055) which links to further duplicates including [Convert javascript dot notation object to nested object](https://stackoverflow.com/questions/7793811/convert-javascript-dot-notation-object-to-nested-object) – pilchard Oct 19 '21 at 17:12
  • And [Javascript: how to dynamically create nested objects using object names given by an array](https://stackoverflow.com/questions/5484673/javascript-how-to-dynamically-create-nested-objects-using-object-names-given-by) (since you can easily split your string to an array) – pilchard Oct 19 '21 at 17:32

1 Answers1

10

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);
Balastrong
  • 4,336
  • 2
  • 12
  • 31
  • Thank you very much, how i can put another object in last {} ? – Hani Oct 19 '21 at 17:11
  • 1
    The second parameter of `reduceRight` as you can see is `""` as you had the empty string in the question. You can change it to whatever you want. In short, the first time `[next]: obj` is executed, you will assign to `locales` (your last key) the value specified. In this case `""`. – Balastrong Oct 19 '21 at 17:13
  • thank you really, I am still new with javascript – Hani Oct 19 '21 at 17:17