繁体   English   中英

如何在 Object 中设置值

[英]How to set value in Object

我必须在 object 中设置值。

这就是问题所在:当我尝试在 object 中写一个有一些 props 的 props 时,以前的 props 将被删除。

我解决了两个案例,还有最后一个。 我需要保存 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);

很少进行更正。

  • 无论创建子 object,都需要推进 object 路径
  • 要检查字符串类型,您需要使用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);

测试currentObj[path[i]] != "string"看起来很奇怪,我想你想改用typeof

在循环内部,您应该在每一步都前进,但如果 object 不存在,则仅创建它。

工作代码:

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

这是你想要的?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM