繁体   English   中英

通过键从对象中删除

[英]Delete from object by key

我试图通过键从对象中删除一个属性。

请务必注意,变量中包含键,并且我无法执行以下操作:

delete obj.test.a

这是我的代码(不起作用)

var obj = {
 b: 2,
   test: {
      a: 1
   }
}

var abc = 'test.a';

delete obj[abc];

console.log(obj);

如何在不进行硬编码的情况下删除obj.test.a,而是从变量中获取密钥。

您可以先将字符串拆分为数组,然后使用reduce()匹配要删除的对象并将其删除。

 var obj = {"b":2,"test":{"a":1}} var abc = 'test.a'.split('.') abc.reduce(function(r, e, i) { if(i == abc.length - 1) delete r[e] return r[e] }, obj) console.log(obj); 

这也许是更优雅的方法

 var obj = {"b":2,"test":{"a":1}} 'test.a'.split('.').reduce(function(r, e, i, arr) { return arr[i + 1] ? r[e] : (delete r[e]) }, obj) console.log(obj); 

解释我的评论的示例:

var obj = {
   test: {
      a: 'hello'
   }
};

function deleteProp(obj, path) {
   var props = path.split('.');
   var currentObj = obj;
   for(var i = 0; i < props.length; i++) {
      var prop = props[i];
      if(i == props.length - 1) {
         delete currentObj[prop];
      } else {
         currentObj = currentObj[prop];
      }
   }
}

deleteProp(obj, 'test.a');
console.log(obj); // { test: {} }

delete obj.test.a适用于我: 在此处输入图片说明

暂无
暂无

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

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