How to efficiently assign a variable depth nested object only with a value and a string of type:
const names = 'obj.source.name'
const value = 'myValue'
To get:
{ obj: { source: { name: 'myValue' } } }
You can also use reduce() method.
const names = 'obj.source.name'
const value = 'myValue'
function nestObj(keys, val) {
var o = {}, k = keys.split('.')
return k.reduce((r, e, i) => r[e] || (r[e] = (k.length-1 != i) ? {} : val), o), o
}
console.log(JSON.stringify(nestObj(names, value), 0, 4))
function nestObject(names, value) {
if (names.length === 0) {
return value;
}
return nestObject(names.splice(0, names.length - 1), { [names.splice(-1)]: value })
}
function nestedProps(name, value) {
if (Array.isArray(name)) {
return nestObject(name, value);
} else {
return nestObject(name.split('.'), value);
}
};
console.log(nestedProps('obj.source.name', 'myValue'));
I personnaly use Lodash for that kind of things.
https://lodash.com/docs/#set does what you are looking for.
_.set({}, 'obj.source.name', 'myValue');
_.set({}, 'obj.source.name', 'myValue');function getObject(path, value) {
let obj = {}, // the result object (the one to return)
_r = obj; // will serve as a reference to a depth
let parts = path.split('.'), // split the path
last = parts.pop(); // remove the last one and store it to be used later to store the value
parts.forEach(p => { // for each part (depth) in the path
_r[p] = {}; // assign an empty object to this depth
_r = _r[p]; // store its reference to be used as the current depth
});
_r[last] = value; // set the value at the last depth
return obj;
}
const names = 'obj.source.name';
const value = 'myValue';
console.log(getObject(names, value));