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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.