亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

如何在對象中設置值

如何在對象中設置值

繁花不似錦 2022-10-27 14:13:19
我必須在對象中設置值。這就是問題所在:當我嘗試在具有一些道具的對象中編寫道具時,以前的道具將被刪除。我解決了兩個案例,還有最后一個。我需要保存 test2。我該如何解決?謝謝。var obj = {  keyOne: "foo",  keyTwo: {    test1: "baz",    test2: {      test21: ["bar"],    }  }}function setObjectProperty(obj, string, value) {  var path = string.split('.');  var currentObj = obj;  for (var i = 0; i < path.length - 1; i++) {    if (!currentObj[path[i]] || currentObj[path[i]] != "string") {      currentObj[path[i]] = {};      currentObj = currentObj[path[i]];    }  }  currentObj[path[path.length - 1]] = value;};setObjectProperty(obj, 'keyOne', 'new');setObjectProperty(obj, 'keyOne.key.key2', 'newnew');setObjectProperty(obj, 'keyTwo.test1', 'zzz');console.log(obj);
查看完整描述

3 回答

?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

很少進行更正。


無論創建子對象,您都需要推進對象路徑

要檢查字符串類型,您需要使用typeof

var obj = {

  keyOne: "foo",

  keyTwo: {

    test1: "baz",

    test2: {

      test21: ["bar"],

    }

  }

}


function setObjectProperty(obj, string, value) {


  var path = string.split('.');

  var currentObj = obj;

  

  for (var i = 0; i < path.length - 1; i++) {

    if (!currentObj[path[i]] || typeof currentObj[path[i]] === 'string') {

      currentObj[path[i]] = {};     

    }

    

     currentObj = currentObj[path[i]];

  }

  currentObj[path[path.length - 1]] = value;

};


setObjectProperty(obj, 'keyOne', 'new');

setObjectProperty(obj, 'keyOne.key.key2', 'newnew');

setObjectProperty(obj, 'keyTwo.test1', 'zzz');


console.log(obj);


查看完整回答
反對 回復 2022-10-27
?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

這個測試currentObj[path[i]] != "string"看起來很奇怪,我想你想用它typeof來代替。


在循環內部,您應該在每一步都前進,但僅在對象不存在時才創建它。


工作代碼:


function setObjectProperty(obj, string, value) {

  var path = string.split('.');

  var currentObj = obj;

  for (var i = 0; i < path.length - 1; i++) {

    if (!currentObj[path[i]] || typeof currentObj[path[i]] == "string") {

      currentObj[path[i]] = {};

    }

    currentObj = currentObj[path[i]];

  }

  currentObj[path[path.length - 1]] = value;

};


查看完整回答
反對 回復 2022-10-27
?
牛魔王的故事

TA貢獻1830條經驗 獲得超3個贊

這是你想要的?


const store = {

  keyOne: "foo",

  keyTwo: {

    test1: "baz",

    test2: {

      test21: ["bar"],

    }

  }

}


function getKeys(key) {

  return key.split(".").filter(k => k.length);

}


function assignProps(object, keys, value = null, root = null) {

  root = root || object;

  

  const key = keys.shift();


  if (!key) return root;


  object[key] = keys.length === 0 ? value : {};


  assignProps(object[key], keys, value, root);

}


assignProps(store, getKeys("keyOne.foo.bar"), "baz");

assignProps(store, getKeys("keyTwo.test1.test2"), "value");


console.log(store);


查看完整回答
反對 回復 2022-10-27
  • 3 回答
  • 0 關注
  • 99 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號