0

Can we store key value pair in javascript in this way? array variable arr;

arr[key1]={value11,value12,value13...}
arr[key2]={value21,value22,value33...}

example:

arr["class"]={8,9,10}
arr["section"]={a,b,c}

and so on...

I am new to javascript.

RKGUPTA
  • 17
  • 1
  • 6
  • Does this answer your question? [Best way to store a key=>value array in JavaScript?](https://stackoverflow.com/questions/1144705/best-way-to-store-a-key-value-array-in-javascript) – Heretic Monkey Aug 17 '20 at 18:07

1 Answers1

2

To store a series or ordered list of values that you're going to index numerically, you'd typically use an array. So for instance, [8, 9, 10] is an array with three entries (the numbers 8, 9, and 10).

To store a keyed set of values, you'd usually use an object (if the set of key/value pairs is reasonably consistent and the keys are strings¹) or a Map (if the set of key/value pairs varies over time, or keys are not strings).

Example of an object with an array of numbers:

const obj = {
    class: [8, 9, 10]
};

or building it up:

const obj = {};
obj.class = [8, 9, 10];
// or
// obj["class"] = [8, 9, 10];

In this case, the key/value pairs are called properties of the object.

Or with a Map:

const map = new Map();
map.set("class", [8, 9, 10]);

In this case, the key/value pairs are called entries of the map.


¹ Technically objects can also have properties keyed by Symbols, but that's not usually something you have to deal with when first getting started.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875