How to convert square bracket object keys into nested object in JavaScript?


We know that there are two ways we can access nested keys within an Object in JavaScript.

For instance, take this object −

const obj = {
   object: {
      foo: {
         bar: {
            ya: 100
         }
      }
   }
};

If we needed to access or update the nested property 'ya', we can access it like −

Way 1 −

obj['object']['foo']['bar']['ya']

orWay 2 −

obj.object.foo.bar.ya

Both these ways lead us to the same destination.

We are required to write a JavaScript function that takes in the path to nested key as a string as depicted by Way 1 and converts it to the notation depicted by Way 2

Example

The code for this will be −

const obj = { "object[foo][bar][ya]": 100 };
const constructDotNotation = obj => {
   const keys = Object.keys(obj)[0].split('[').map(el => {
      return el.replace(']', '');
   });
   let res = {};
   keys.reverse().forEach(key => {
      if (Object.keys(res).length === 0){
         res[key] = obj[Object.keys(obj)[0]];
      }else{
         const temp = {};
         temp[key] = res;
         res = temp;
      };
   });
   return res;
};
console.log(JSON.stringify(constructDotNotation(obj), undefined, 4));

Output

And the output in the console will be −

{
   "object": {
      "foo": {
         "bar": {
            "ya": 100
         }
      }
   }
}

Updated on: 20-Nov-2020

629 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements