Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
75
rated 0 times [  77] [ 2]  / answers: 1 / hits: 48926  / 12 Years ago, mon, september 3, 2012, 12:00:00

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


More From » arrays

 Answers
66

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.


[#83272] Saturday, September 1, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austynp

Total Points: 505
Total Questions: 118
Total Answers: 106

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
austynp questions
;