3 回答
TA贡献1993条经验 获得超5个赞
var obj = {
a: {
b: {
c: 3
}
}
}
var text = 'a.b.c'
function setData(obj, config) {
let keys = Object.keys(config)
keys.forEach(key => {
cur = obj
let names = key.split('.')
let last = names.length - 1
names.forEach((name, index) => {
if (!cur[name]) cur[name] = {}
if (last === index) {
cur[name] = config[key]
} else {
cur = cur[name]
}
})
})
}
setData(obj, {[text]: 4, 'e.f': 6}) // obj: {a:{b:{c:4}},e:{f:6}}}
TA贡献1833条经验 获得超4个赞
function setObjfromText(obj,text,value){
let temp=obj
let textgroup = text.split('.')
let l = textgroup.length
for(let i=0;i<l-1;i++){
temp[textgroup[i]] = typeof(temp[textgroup[i]])=='object'?temp[textgroup[i]]:{}
temp = temp[textgroup[i]]
}
temp[textgroup[l-1]] = temp[textgroup[l-1]] | value
return obj
}
TA贡献1825条经验 获得超6个赞
function setObjText(o,t,v){ //因为是设置,所以我理解已经有这个结构否则需要保证路径上各级都是对象
let tmp=o;
let t2k=t.split('.');
for(let i=0;i<t2k.length;i++){
tmp[t2k[i]]=typeof(tmp[t2k[i]])=='object'?tmp[t2k[i]]:{} ;
tmp=tmp[t2k[i]];
}
tmp=value;
}
添加回答
举报