Given a JS string: var s = "deep.deeper.deepest", how can I convert this into object like this: deep: {deeper: {deepest: {}}}
Asked
Active
Viewed 56 times
0
dovstone
- 117
- 10
2 Answers
2
const dottedToObj = (str, orig = {}) => (str.split(".").reduce((obj, key) => obj[key] = {}, orig), orig);
Just reduce the array of strings (splitted the original string) into a chain of objects. Or a bit less functional:
function dottedToObj(str){
const root = {};
var acc = root;
for(const key of str.split(".")){
acc = acc[key] = {};
}
return root;
}
Jonas Wilms
- 120,546
- 16
- 121
- 140
-
[Try it](http://jsbin.com/wizekubabi/edit?console) – Jonas Wilms Jan 04 '18 at 17:52
1
A simple loop should work for this, just move through each dotted property while moving down one level in the object:
const s = "deep.deeper.deepest";
function convertToObject(str) {
const result = {};
let inner = result;
for (const key of s.split(".")) {
// Give the object a child with this key
inner[key] = {};
// Set the current object to that child.
inner = inner[key]
}
// Return the original
return result;
}
console.log(convertToObject(s))
CRice
- 26,396
- 4
- 55
- 62