P
P
propovednik2011-10-20 10:01:40
JavaScript
propovednik, 2011-10-20 10:01:40

Creating an associative array in JS?

How to create an associative array in JS inline? I honestly searched and couldn't find it.
An example of what I want in neutral PHP:

$arrArray = array(&quot;key1&quot; =&gt; &quot;value1&quot;, &quot;key2&quot; =&gt; &quot;value2&quot;)<br/>
Interested in a short path and in one operation

Answer the question

In order to leave comments, you need to log in

6 answer(s)
S
Sergey, 2011-10-20
@propovednik

var arr = { key1: 'value1', key2: 'value2' };

K
Krio, 2011-10-20
@Krio

<script type="text/javascript">
var arrArray1 = <?php echo json_encode($arrArray);?>;
var arrArray2 = {
  key1: 'value1'
  ,key2: 'value2'
};
var arrArray3 = [];
arrArray3['key1'] = 'value1';
arrArray3['key2'] = 'value2';
</script>

M
Mikhail Krainov, 2011-10-20
@medved13

There are no pure associative arrays in JS.
There are objects that store key-value pairs, but there are no length, pop, shift, etc. properties.
And there are arrays that do not have keys, but have all the charms of real arrays.

M
Masterkey, 2011-10-21
@Masterkey

For anyone else , check this out , and then it 's better to read the mana on MDN .

L
lorenIpsum, 2015-04-21
@lorenIpsum

I propose here such a crutch
//key=>value; key=>value;
function array_assoc(data){
var _arr = [];
var a = data split(";");
for(var c = 0; c < a.length; c++){
var b = a[c].split("=>");
_arr[b[0]] = b[1];
}
return_arr;
}
var my_array = array_assoc("name=>Vasya;age=16;gender=male");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question