
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 } } } }
Advertisements