简体   繁体   English

通过键从对象中删除

[英]Delete from object by key

I am trying to remove a property from the object by key. 我试图通过键从对象中删除一个属性。

It's very important to notice that I have the key in my variable, and i am unable to do the following: 请务必注意,变量中包含键,并且我无法执行以下操作:

delete obj.test.a

This is my code (which doesn't work) 这是我的代码(不起作用)

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

var abc = 'test.a';

delete obj[abc];

console.log(obj);

How can I acheive deleting obj.test.a without hardcoding, and instead taking the key from variable. 如何在不进行硬编码的情况下删除obj.test.a,而是从变量中获取密钥。

You can first split you string to array and then use reduce() to match object you want to delete and delete it. 您可以先将字符串拆分为数组,然后使用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); 

Here is maybe more elegant approach 这也许是更优雅的方法

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

Example explaining my comment: 解释我的评论的示例:

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 works for me: delete obj.test.a适用于我: 在此处输入图片说明

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

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