Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push an associative item into an array in JavaScript

Tags:

javascript

People also ask

Can you push an object into an array JavaScript?

To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr. push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.

How do you write associative array in JavaScript?

An associative array is declared or dynamically createdWe can create it by assigning a literal to a variable. var arr = { "one": 1, "two": 2, "three": 3 }; Unlike simple arrays, we use curly braces instead of square brackets. This has implicitly created a variable of type Object.

Does JavaScript support associative array?

JavaScript does not support associative arrays. You should use objects when you want the element names to be strings (text). You should use arrays when you want the element names to be numbers.


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 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"]);​

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];