2 回答

TA貢獻1829條經(jīng)驗 獲得超4個贊
我的猜測是你正在尋找
if (typeof object[keyy] != "obect")
而不是
if (typeof object[keyy] == "undefined")
它不會檢測到當前是屬性值的字符串。
當然調(diào)用set(obj, "hello.world.again", "hello again")
會導致{"hello": {"world": {"again": "hello again"}}}
,不會{"hello": {"world": {"again": "test"}}}
。

TA貢獻1884條經(jīng)驗 獲得超4個贊
我發(fā)現(xiàn)您的邏輯需要一個 JSON 對象但接收字符串值,它需要修改一點或設(shè)置像這樣的值{again: 'hello again'}。
我試著簡單地寫下這個set 方法,它可能對某人有幫助!
function set(obj, key, value) {
let keys = key.split('.');
if(keys.length<2){ obj[key] = value; return obj; }
let lastKey = keys.pop();
let fun = `obj.${keys.join('.')} = {${lastKey}: '${value}'};`;
return new Function(fun)();
}
var obj = {
"hello": {
"world": "test"
}
};
set(obj, "hello.world.again", 'hello again'); // Value should be object here
console.log(obj);
set(obj, "hello.world.again.onece_again", 'hello once again');
console.log(obj);
添加回答
舉報