How to create an associative array in JavaScript literal notation
Asked Answered
T

8

96

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?
Tricho answered 29/5, 2016 at 23:41 Comment(6)
What is wrong with using this? var myNewArray = {'a': 200, 'b': 300};Stature
@Stature - that works, but I'm trying to understand why it does not work with array notation[] ?Tricho
You want an object, not an array.Radionuclide
The array notation is only list of elements between []. Nothing more and nothing less. That is just how javascript arrays are.Bartolemo
Don't know why someone downvoted my question? what is wrong with this?Tricho
@SLaks, MT0, BoltKey - thank you, yes I can use an object. :)Tricho
N
125

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.

Non answered 29/5, 2016 at 23:48 Comment(13)
javascript has first class arrays, so noRhythmist
no what? they are first class but still implemented as objects. See [] instanceof Object === true!Non
yep, everything is an object in JS land, except nullRhythmist
@self Tell typeof null that. Also, primitives like string, boolean, and number are not normally considered objects either.Hydrastine
but they are objects, just not object instances usuallyRhythmist
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().Bartolemo
yes null and undefined is an object but is an exceptionRhythmist
@self undefined is definitely not an object. Primitives aren't really either: #17256682Hydrastine
primitives are objects but not instancesRhythmist
@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.Non
@Non it's not the same bottom line, objects properties are under ordered where an array is an ordered sequence. don't spew ignorance please: #5526295. length is read only man, so you're comment is completely wrongRhythmist
@self thats just wrong! The order of an integer indexes on objects is also specified. 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!Non
With the first method you wont have access to most array methods like length, join, etc. But It surly quenches the questioner's thirst.Will
V
48

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'
Vermin answered 23/1, 2018 at 9:3 Comment(3)
This is perfect but just remember it does not work in Internet ExplorerToxin
@TaylorA.Leach, It would work with Babel transpilation, wouldn't it?Paralysis
It's supported by most the modern browsers, check this page: caniuse.com/#search=Map But you can use Babel compiler to compile into ES5.Vermin
K
8

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

Kloof answered 29/5, 2016 at 23:44 Comment(0)
P
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.

Phipps answered 29/5, 2016 at 23:46 Comment(0)
G
0

I achieved this by using objects. Your create an object, and loop through using for in loop. each x will be the index and holder[x] will be the value. an example is below.

var test = {'hello':'world','hello2':'world2'}
for(let x in holder)
{
  let inxed = x;
  let value = holder[x]
  console.log('index ' + x + ' has value of ' +    value)
}
Glanders answered 16/6, 2022 at 10:56 Comment(0)
G
0

Try these examples in the console:

var A = [];
A["1"] = "abc"
A.length
A

A.length is 2 and A is [empty, 'abc']. Now try

A["2a"] = "abc"
A.length
A

A.length is 2 again and A is [empty, 'abc', 2a: 'abc']. Finally checkout

A["2"] = "efg"
A.length
A

A.length is 3 and A is [empty, 'abc', 'efg', 2a: 'abc']

You can even try

for (a of A) console.log(a)

to obtain undefined abc efg undefined

As already said by others, probably you just need a JavaScript object to map strings to values.

Geneticist answered 12/3 at 9:33 Comment(0)
B
-1

Associate array is an array indexed with name similar to an object instead of numbers like in regular array. You can create an associative array in the following way:

var arr = new Array(); // OR var  arr  = [];
arr['name'] = 'david'
arr['age'] = 23;

console.log(arr['name']);
Berm answered 1/8, 2021 at 7:22 Comment(1)
The question is asking how to do it in a single step; the OP has shown in the question they know how to create an array and then assign arbitrary properties to it one by one (and their code doesn't have the error in it that yours does).Quixotism
A
-3

You can do what you wanted to do this way:

myNewArray = new Array ({'a' : 200, 'b' : 300})
Archdeaconry answered 17/12, 2019 at 14:3 Comment(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 200Combat

© 2022 - 2024 — McMap. All rights reserved.