Bernie Bernie - 1 year ago 86
JSON Question

Add field to JSON

I want to add a field to JSON. I do have a working solution, but it's ugly (using eval). Is there a nicer way to add a field?

var json = {};
var id = "test";
eval("json." + id + " = 5;");

UPDATE: Sorry, my question was somewhat unclear.
I want to use the variable id, which has the value of the new field.


Answer Source

You can use like below instead:


json[id] = 5;