67

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

1
  • It does assign val to the key "name", but in JS: console.log(arr.name); Commented Mar 22, 2018 at 17:30

5 Answers 5

125

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/

Sign up to request clarification or add additional context in comments.

6 Comments

You should rename arr to obj. Because it's an object, not an array.
You know, at times we get so focused on complex solutions that we forget the simple ones. arr[name] = val; 5 years later thank you brother. Combined with a for cycle you can shove variables one after another all day
Using this method doesn't do a proper push as the question implies. The array gets built in the order that it wants to instead of pushing the new value onto the end.
@jgreep What is the question implying? Where is any reference to the order of the array? I don't follow your comment.
@VisioN The question says "push." That implies a formal stack structure with a pop and push, where order is important. Although, I concede that the context of the question shows that order is not a priority. In that respect, your answer is appropriate and the question is misleading. I provided an answer below that solves the problem using a stack approach.
|
28

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

Comments

7

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.

2 Comments

This is not an array. The presence of non-numeric keys renders this an object literal. See for yourself: console.log(typeof myArray);. Also, the length property will not count these non-numeric keys as part of the array: console.log(myArray.length); returns 0. Add myArray[0] = 'see';, then run again, it returns 1.
You guys dipute about naming? Is it an object? An array? Well, w3schools.com/jsref/jsref_obj_array.asp calls it an Array Object. :))
2

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

1 Comment

This is the only solution that worked for me.
1

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

1 Comment

This only works if 'name' is defined. If you want to push a new entry onto the object, this will not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.