44

I im building and array where my array key is from a variable like this:

var art = $('#article_id').val();
var stk =  $('#stk').val();
elements ={ art : stk };
alert(elements[art]);

but i end up with this output art=>50 instead of 5123=>50

Barta Tamás
  • 889
  • 4
  • 15
  • 36
  • 2
    Could you please change the title as this question has nothing to do with arrays but with objects. Thx – velop Aug 07 '16 at 19:23

2 Answers2

84

ECMAScript 2015 (aka ES6 Harmony)

ES 2015 provides support for this through a feature called computed property names (although the relevant section of the spec is called "Object Initializer").

Simply put, surround the variable (in general, any expression) with square brackets to evaluate it and use the result as a property name. In your example that would be

elements = { [art]: stk };

Original answer (targeting ES5)

You cannot create object literals like that. You need to write

elements = {};
elements[art] = stk;

The reason why elements = { art: stk } does not work is because it is equivalent to elements = { "art": stk } (with quotes). The two versions are equivalent in JavaScript as long as art is a legal identifier, and the second version makes it clear what's going on.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • 1
    Update: ECMAScript 2015 added support for _Computed property names_. The answer can now be written as `elements = { [art]: stk };`. See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names – searlea Jan 14 '17 at 19:13
  • @searlea: Thank you for the heads up! I updated the answer to include this information. – Jon Jan 26 '17 at 10:37
13

Use below to add dynamic key to an object.

elements = {};
elements[art] = stk;
xdazz
  • 158,678
  • 38
  • 247
  • 274