Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I turn a string in dot notation into a nested object with a value – JavaScript?
Converting a dot-notation string into a nested object is a common task in JavaScript. This approach uses split() and map() to dynamically build the nested structure.
Problem Setup
Let's say we have a dot-notation string representing nested property keys:
const keys = "details1.details2.details3.details4.details5"; const firstName = "David";
We want to create a nested object where the final property gets the value "David".
Solution Using split() and map()
The technique involves splitting the dot-notation string and using map() to build nested objects:
const keys = "details1.details2.details3.details4.details5";
const firstName = "David";
var tempObject = {};
var container = tempObject;
keys.split('.').map((k, i, values) => {
container = (container[k] = (i == values.length - 1 ? firstName : {}))
});
console.log(JSON.stringify(tempObject, null, ' '));
{
"details1": {
"details2": {
"details3": {
"details4": {
"details5": "David"
}
}
}
}
}
How It Works
The algorithm works by maintaining a reference (container) that moves deeper into the nested structure:
-
keys.split('.')creates an array:['details1', 'details2', 'details3', 'details4', 'details5'] - For each key, create a new nested object (or assign the final value)
-
containerreference moves to the newly created nested object - On the last iteration, assign the actual value instead of an empty object
Alternative Approach Using reduce()
Here's a cleaner version using reduce():
function createNestedObject(keys, value) {
return keys.split('.').reduceRight((acc, key) => {
return { [key]: acc };
}, value);
}
const keys = "details1.details2.details3.details4.details5";
const result = createNestedObject(keys, "David");
console.log(JSON.stringify(result, null, 2));
{
"details1": {
"details2": {
"details3": {
"details4": {
"details5": "David"
}
}
}
}
}
Conclusion
Both approaches effectively convert dot-notation strings to nested objects. The reduce() method provides a more functional programming approach, while the map() solution offers step-by-step control over the nesting process.
