有点晚了,但这是一个非图书馆的,更简单的答案:
/**
* Dynamically sets a deeply nested value in an object.
* Optionally "bores" a path to it if its undefined.
* @function
* @param {!object} obj - The object which contains the value you want to change/set.
* @param {!array} path - The array representation of path to the value you want to change/set.
* @param {!mixed} value - The value you want to set it to.
* @param {boolean} setrecursively - If true, will set value of non-existing path as well.
*/
function setDeep(obj, path, value, setrecursively = false) {
path.reduce((a, b, level) => {
if (setrecursively && typeof a[b] === "undefined" && level !== path.length){
a[b] = {};
return a[b];
}
if (level === path.length){
a[b] = value;
return value;
}
return a[b];
}, obj);
}
我制作的这个功能可以完全满足您的需求,而且还可以做得更多。
假设我们要更改深度嵌套在此对象中的目标值:
let myObj = {
level1: {
level2: {
target: 1
}
}
}
所以我们会像这样调用我们的函数:
setDeep(myObj, ["level1", "level2", "target1"], 3);
将导致:
myObj = { level1: { level2: { target: 3 } } }
如果对象不存在,将 set recursively 标志设置为 true 将设置对象。
setDeep(myObj, ["new", "path", "target"], 3, true);
将导致:
obj = myObj = {
new: {
path: {
target: 3
}
},
level1: {
level2: {
target: 3
}
}
}