第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Javascript設(shè)置嵌套對象鍵

Javascript設(shè)置嵌套對象鍵

德瑪西亞99 2022-10-27 15:14:42
代碼:module.exports.set = function (data, key, value) {    if (key.includes(".")) {        let elements = key.split(".");      let element = elements.pop();      let obj = elements.reduce((object, keyy) => {        if (typeof object[keyy] == "undefined") object[keyy] = {};          return object[keyy];      }, data);        obj[element] = value;        return data;    } else {      data[key] = value;        return data;    }}我將通過示例向您解釋問題。var obj = {};set(obj, "hello.world", "test")console.log(obj)控制臺日志:{    "hello": {        "world": "test"    }}但是如果我寫這段代碼:var obj = {    "hello": {        "world": "test"    }};set(obj, "hello.world.again", "hello again")console.log(obj)對象沒有變化??刂婆_日志將是這樣的:var obj = {    "hello": {        "world": "test"    }};我想要這樣的結(jié)果:{    "hello": {        "world": {            "again": "test"        }    }}在 lodash 模塊中,我可以做我所說的事情。但在我的代碼中,我不能這樣做。請幫助我,我該怎么做?
查看完整描述

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"}}}。


查看完整回答
反對 回復 2022-10-27
?
慕村9548890

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);


查看完整回答
反對 回復 2022-10-27
  • 2 回答
  • 0 關(guān)注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號