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": ""
        }
      }
    }
  }
}
2

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much, how i can put another object in last {} ?
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 "".
thank you really, I am still new with javascript

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.