46

I understand that there are no associative arrays in JavaScript, only objects.

However I can create an array with string keys using bracket notation like this:

var myArray = [];
myArray['a'] = 200;
myArray['b'] = 300;
console.log(myArray); // Prints [a: 200, b: 300]

So I want to do the exact same thing without using bracket notation:

var myNewArray = [a: 200, b: 300]; // I am getting error - Unexpected token:

This does not work either:

var myNewArray = ['a': 200, 'b': 300]; // Same error. Why can I not create?
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Wild Widow
  • 1,926
  • 2
  • 16
  • 29

6 Answers6

61

JavaScript has no associative arrays, just objects. Even JavaScript arrays are basically just objects, just with the special thing that the property names are numbers (0,1,...).

So look at your code first:

var myArray = []; // Creating a new array object
myArray['a'] = 200; // Setting the attribute a to 200
myArray['b'] = 300; // Setting the attribute b to 300

It's important to understand that myArray['a'] = 200; is identical to myArray.a = 200;!

So to start with what you want: You can't create a JavaScript array and pass no number attributes to it in one statement.

But this is probably not what you need! Probably you just need a JavaScript object, what is basically the same as an associative array, dictionary, or map in other languages: It maps strings to values. And that can be done easily:

var myObj = {a: 200, b: 300};

But it's important to understand that this differs slightly from what you did. myObj instanceof Array will return false, because myObj is not an ancestor from Array in the prototype chain.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Lux
  • 16,183
  • 3
  • 36
  • 64
  • 1
    javascript has first class arrays, so no – Ryan McCullagh May 29 '16 at 23:50
  • no what? they are first class but still implemented as objects. See `[] instanceof Object === true`! – Lux May 29 '16 at 23:52
  • yep, everything is an object in JS land, except null – Ryan McCullagh May 29 '16 at 23:55
  • 1
    @self Tell `typeof null` that. Also, primitives like string, boolean, and number are not normally considered objects either. – Alexander O'Mara May 29 '16 at 23:57
  • 1
    but they are objects, just not object instances usually – Ryan McCullagh May 29 '16 at 23:57
  • 4
    I would just like to add that when you create an array like `[1, 2, 3, 'foo']`, it is not identical to {0: 1, 1: 2, 2: 3, 3: "foo"}, mainly because of the array-specific functions like `array.push()` or `array.slice()`. – BoltKey May 29 '16 at 23:57
  • yes null and undefined is an object but is an exception – Ryan McCullagh May 29 '16 at 23:59
  • 1
    @self `undefined` is definitely not an object. Primitives aren't really either: http://stackoverflow.com/questions/17256182/what-is-the-difference-between-string-literals-and-string-objects-in-javascript – Alexander O'Mara May 30 '16 at 00:02
  • 1
    primitives are objects but not instances – Ryan McCullagh May 30 '16 at 00:05
  • @self still nothing wrong on my statement. `Array.prototype.push` is basically just `this[this.length] = arguments[0];this.length++;`. You can also do this manually and the array functions will just work as you have used it. Its just sugar around objects. – Lux May 30 '16 at 00:07
  • @Lux it's not the same bottom line, objects properties are under ordered where an array is an ordered sequence. don't spew ignorance please: http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order. `length` is read only man, so you're comment is completely wrong – Ryan McCullagh May 30 '16 at 00:22
  • 1
    @self thats just wrong! The [order of an integer indexes on objects is also specified](http://www.ecma-international.org/ecma-262/6.0/#sec-ordinary-object-internal-methods-and-internal-slots-ownpropertykeys). The specification does not differ for arrays. The only difference is the constructor and the prototype with all the fancy array methods, which also work fine for non arrays! – Lux May 30 '16 at 00:40
25

You can use Map:

var arr = new Map([
   ['key1', 'User'],
   ['key2', 'Guest'],
   ['key3', 'Admin'],
]);

var res = arr.get('key2');
console.log(res); // The value is 'Guest'
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Santo Boldizar
  • 907
  • 10
  • 14
3

You want to use an object in this case

var myObject = {'a' : 200, 'b' : 300 };

This answer links to a more in-depth explanation: How to do associative array/hashing in JavaScript

httpNick
  • 2,372
  • 1
  • 19
  • 34
2

Well, you are creating an array, which is in fact an object:

var arr = [];
arr.map;
// function(..)
arr['map'];
// function(..)

arr['a'] = 5;

console.log(arr instanceof Object); // true

You can add fields and functions to arr. It does not "insert" them into the array though (like arr.push(...)).

You can refer to an object fields with the [] syntax.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
galchen
  • 5,122
  • 3
  • 24
  • 40
2

Arrays and Objects are different things.

For an object, you can do things like:

var obj = { "property1": "value1" };
obj.property2 = "value2";

For arrays, you have to do this:

var arr = [];
arr[0] = "value";
developius
  • 960
  • 8
  • 17
-1

You can do what you wanted to do this way:

myNewArray = new Array ({'a' : 200, 'b' : 300})
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
milen
  • 1
  • this doesnt work as requested by op. you would need to access the items by index then by key. so to get the value '200' you would need to do myNewArray[0]['a']. the op wants to access as myNewArray['a'] to get the value 200 – Heriberto Lugo Oct 25 '20 at 15:35