Click Upvote Click Upvote - 4 years ago 82
Javascript Question

Best way to store a key=>value array in JavaScript?

What's the best way to store a

array in javascript, and how can that be looped through?

The key of each element should be a tag, such as
or just
and the value should be the numerical value of the id.

It should either be the element of an existing javascript class, or be a global variable which could easily be referenced through the class.

jQuery can be used.

Answer Source

That's just what a JavaScript object is:

var myArray = {id1: 100, id2: 200, "tag with spaces": 300};
myArray.id3 = 400;
myArray["id4"] = 500;

You can loop through it using loop:

for (var key in myArray) {
  console.log("key " + key + " has value " + myArray[key]);

See also: Working with objects (MDN).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download