1

Fiddle

var json = {name: 'chan'};
var variable = 'age';

$.extend(json, {[variable]: 35});

$('#result').html(JSON.stringify(json));

This method works on most popular browsers except IE, I need to define object key dynamically, how to make it work on IE?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Chan
  • 1,947
  • 6
  • 25
  • 37

2 Answers2

8

The [] notation for property names in object initializers is an ES2015 feature, and older versions of Internet Explorer don't support it. (Older versions of all browsers don't support it; there are lots of mobile devices that would also consider that an error.)

You can however use [ ] in a property assignment expression:

json[variable] = 35;

That should work everywhere.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • thanks, if I want to add more object should be `json[variable] = {age: 35: height 180};`, right? – Chan Oct 09 '15 at 12:26
  • @Chan that will set the value of one single property to that object. I will extend the answer. – Pointy Oct 09 '15 at 12:27
  • @Chan well now I am not sure I understand your question. If you want to set the properties "age" and "height" on the `json` object, you can use `$.extend()` with that object literal. – Pointy Oct 09 '15 at 12:29
  • never mind ha, I just need to remember better not use `{[variable]: 35}` format, may I ask one more question, in the past I remembered if I don't clear the last comma in array of object, it will be error in IE, for example, `var arrs = ['a', 'b',];`, I just find out IE 11 is fine with that, is it ok right now? – Chan Oct 09 '15 at 12:49
  • @Chan yes new versions of IE are OK with extra `,` at the end of the list - **BUT** IE may interpret that differently! Try `["a", "b",].length` - in IE that *might* be `3` instead of `2`! – Pointy Oct 09 '15 at 13:00
2

Just do that: json[variable] = 35 instead of $.extend(json, {[variable]: 35});.

This should work in IE.

divoom12
  • 802
  • 4
  • 12