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
How do I turn a string in dot notation into a nested object with a value – JavaScript?
Let’s say the following is our string in dot notation −
const keys = "details1.details2.details3.details4.details5"
And the following is our array −
const firsName = "David";
To turn into a nested object, use the concept of split(‘.’) along with map().
Example
Following is the code −
const keys = "details1.details2.details3.details4.details5"
const firsName = "David";
var tempObject = {};
var container = tempObject;
keys.split('.').map((k, i, values) => {
container = (container[k] = (i == values.length - 1 ? firsName : {}))
});
console.log(JSON.stringify(tempObject, null, ' '));
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo227.js.
Output
The output is as follows −
PS C:\Users\Amit\JavaScript-code> node demo227.js
{
"details1": {
"details2": {
"details3": {
"details4": {
"details5": "David"
}
}
}
}
}Advertisements