简单的while循环set Object 属性 (有则合并,无则
2022-10-28 本文已影响0人
Spidd
function setDescendantProp(obj, desc, fun) {
const arr = desc.split('.');
let prop = arr.shift();
// 循环路径赋值
while (arr.length){
if(!obj[prop]){
obj[prop] = {};
}
// eslint-disable-next-line no-param-reassign
obj = obj[prop]
prop = arr.shift();
}
obj[prop] = fun;
}
path:目标位置
value:目标值
obj:目标
function editFn(path, value, obj) {
const arr = path.split('.')
const len = arr.length - 1
arr.reduce((cur, key, index) => {
if (!(cur[key]))
throw `${key} 不存在!`
if (index === len) {
cur[key] = value
}
return cur[key]
}, obj)
}