Push an associative item into an array in JavaScript

JavaScript doesn't have associate arrays. You need to use Objects instead:

var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);​

To get value you can use now different ways:

console.log(obj.name);​
console.log(obj[name]);​
console.log(obj["name"]);​

To make something like associative array in JavaScript you have to use objects. ​

var obj = {}; // {} will create an object
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);

DEMO: http://jsfiddle.net/bz8pK/1/


JavaScript has associative arrays.

Here is a working snippet.

<script type="text/javascript">
  var myArray = [];
  myArray['thank'] = 'you';
  myArray['no'] = 'problem';
  console.log(myArray);
</script>

They are simply called objects.


Another method for creating a JavaScript associative array

First create an array of objects,

 var arr = {'name': []};

Next, push the value to the object.

  var val = 2;
  arr['name'].push(val);

To read from it:

var val = arr.name[0];

Tags:

Javascript