如何仅使用值和字符串类型:
有效地分配变量深度嵌套对象const names = 'obj.source.name'
const value = 'myValue'
获得:
{ obj: { source: { name: 'myValue' } } }
答案 0 :(得分:2)
您也可以使用reduce()
方法。
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))
答案 1 :(得分:1)
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'));
答案 2 :(得分:0)
答案 3 :(得分:0)
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));