3 回答

TA貢獻1993條經驗 獲得超6個贊
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;
}
添加回答
舉報