Push an associative item into an array in JavaScript

Javascript

Javascript Problem Overview


How can I correct the following code?

var arr = [];
var name = "name";
var val = 2;
arr.push(val); //works , but not associative
arr[name] = val; //does not work
console.log(arr);

JSFiddle

Javascript Solutions


Solution 1 - Javascript

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/

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

Solution 3 - Javascript

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.

Solution 4 - Javascript

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

Solution 5 - Javascript

If you came to this question searching for a way to push to the end of an associative array while preserving the order, like a proper stack, this method should work. Although the output is different than the original question, it is still possible to iterate through.

// Order of entry altered
let obj = {}; //  will create an object
let name = "4 name";
let val = 4;
obj[val] = name;
name = "7 name";
val = 7;
obj[val] = name;
name = "2 name";
val = 2;
obj[val] = name;
console.log(obj);

// Order of entry maintained for future iteration
obj = []; //  will create an array
name = "4 name";
val = 4;
obj.push({[val]:name}); // will push the object to the array
name = "7 name";
val = 7;
obj.push({[val]:name});
name = "2 name";
val = 2;
obj.push({[val]:name});
console.log(obj);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser669677View Question on Stackoverflow
Solution 1 - JavascriptVisioNView Answer on Stackoverflow
Solution 2 - JavascriptantyratView Answer on Stackoverflow
Solution 3 - JavascriptAlessandro FlatiView Answer on Stackoverflow
Solution 4 - Javascriptpingle60View Answer on Stackoverflow
Solution 5 - JavascriptjgreepView Answer on Stackoverflow