1

how to delete a particular json element by variable:
i.e. I want to delete obj.a.b, but it is passed by a variable.
Is there a simple way to implement this?

var t = 'obj.a.b';
var obj = {a: {b: 'b', b2: 'b2'}};
delete t;  // not work here
console.log(JSON.stringify(obj));
Lune
  • 241
  • 1
  • 3
  • 13

1 Answers1

1

If you trust the value of t, you can use the eval(...) function to execute dynamic code like this:

var t = 'obj.a.b';
var obj = {a: {b: 'b', b2: 'b2'}};
eval("delete " + t + ";");
console.log(JSON.stringify(obj));

Note that if you cannot trust the value of t (e.g. it's a user-supplied value), an attacker can inject code by supplying a malicious value for t. You have to use eval(...) carefully as it can easily lead to such code-injection attack. This answer has good discussion about how and when to use eval.

Community
  • 1
  • 1
Saeed Jahed
  • 821
  • 5
  • 8