Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: variable as array key

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

like image 752
Barta Tamás Avatar asked Sep 03 '12 08:09

Barta Tamás


People also ask

Can I use a variable as a key JavaScript?

Use Variable as Key for Objects in JavaScript log(obj. key); console. log(obj["key"]); The variable varr was set as the key for the object obj .

Can you put variables in an array JavaScript?

Array Elements Can Be ObjectsJavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array.

Is key in array JavaScript?

JavaScript Array keys()The keys() method returns an Array Iterator object with the keys of an array. The keys() method does not change the original array.

How do you create a key value pair from an array?

const arr = [ {"name": "Rahul", "score": 89}, {"name": "Vivek", "score": 88}, {"name": "Rakesh", "score": 75}, {"name": "Sourav", "score": 82}, {"name": "Gautam", "score": 91}, {"name": "Sunil", "score": 79}, ];


2 Answers

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.

like image 94
Jon Avatar answered Oct 19 '22 16:10

Jon


Use below to add dynamic key to an object.

elements = {}; elements[art] = stk; 
like image 44
xdazz Avatar answered Oct 19 '22 15:10

xdazz