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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
Original answer (targeting ES5)
You cannot create object literals like that. You need to write
The reason why
elements = { art: stk }does not work is because it is equivalent toelements = { "art": stk }(with quotes). The two versions are equivalent in JavaScript as long asartis a legal identifier, and the second version makes it clear what’s going on.