1

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.

rossanmol
  • 1,633
  • 3
  • 17
  • 34

2 Answers2

1

You can first split you string to array and then use reduce() to match object you want to delete and delete it.

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);
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

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: {} }
Arg0n
  • 8,283
  • 2
  • 21
  • 38