close

How to create an associative array in JavaScript literal notation

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to create an associative array in JavaScript literal notation in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to create an associative array in JavaScript literal notation ?

  1. How to create an associative array in JavaScript literal notation ?

    to create an associative array in JavaScript literal notation 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'

  2. How to create an associative array in JavaScript literal notation ?

    to create an associative array in JavaScript literal notation 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'

Method 1

avaScript 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.

Method 2

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'

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment