358

What's the best way to store a key=>value array in javascript, and how can that be looped through?

The key of each element should be a tag, such as {id} or just id 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.

5
  • A hash iterated with $.each won't do? This is pretty much standard. Jul 17, 2009 at 17:38
  • 32
    Why in the world would you want to use jQuery for this simple basic task, kgiannakakis? Jul 17, 2009 at 17:42
  • 8
    If your using jQuery anyway iterating with $.each is just nicer than a simple for loop. Jul 17, 2009 at 17:47
  • @kgiannakakis Very simple reasoning but not so obvious for everyone, as it can be saw here. ;-)
    – sdlins
    Mar 25, 2018 at 17:15
  • 4
    @kgiannakakis Or instead of using jQuery to loop over an array, you could use JavaScript's builtin Array.prototype.forEach
    – jotch
    Mar 27, 2019 at 0:18

7 Answers 7

595

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 for..in loop:

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

See also: Working with objects (MDN).

In ECMAScript6 there is also Map (see the browser compatibility table there):

  • An Object has a prototype, so there are default keys in the map. This could be bypassed by using map = Object.create(null) since ES5, but was seldomly done.

  • The keys of an Object are Strings and Symbols, where they can be any value for a Map.

  • You can get the size of a Map easily while you have to manually keep track of size for an Object.

7
  • 29
    If your browser supports it (IE9 and up), it is safer to create the empty object first with var foo = Object.create(null) and then add properties to it like foo.bar = "baz". Creating an object with {} is equivalent to Object.create(Object.prototype), which means that it inherits all properties of Object. Normally that is not a problem, but it could cause your object to have unexpected keys if some library has modified the global Object.prototype. Aug 12, 2014 at 3:00
  • 1
    @RoryO'Kane you could use hasownproperty to get around that.
    – user3186555
    Apr 22, 2016 at 10:11
  • 7
    @DaMaxContent you could also turn right by turning left three times. Jul 8, 2016 at 3:39
  • 1
    @thenaglecode Sometimes left 3 times works. Imagine if you couldn't turn right? Or you had to do it more than once?
    – user3186555
    Jul 8, 2016 at 5:26
  • 1
    But perhaps OP wanted an array since objects wont keep the order of items consistently across browser implementations?
    – trainoasis
    Apr 22, 2020 at 9:31
119

If I understood you correctly:

var hash = {};
hash['bob'] = 123;
hash['joe'] = 456;

var sum = 0;
for (var name in hash) {
    sum += hash[name];
}
alert(sum); // 579
1
80

You can use Map.

  • A new data structure introduced in JavaScript ES6.
  • Alternative to JavaScript Object for storing key/value pairs.
  • Has useful methods for iteration over the key/value pairs.
var map = new Map();
map.set('name', 'John');
map.set('id', 11);

// Get the full content of the Map
console.log(map); // Map { 'name' => 'John', 'id' => 11 }

Get value of the Map using key

console.log(map.get('name')); // John 
console.log(map.get('id')); // 11

Get size of the Map

console.log(map.size); // 2

Check key exists in Map

console.log(map.has('name')); // true
console.log(map.has('age')); // false

Get keys

console.log(map.keys()); // MapIterator { 'name', 'id' }

Get values

console.log(map.values()); // MapIterator { 'John', 11 }

Get elements of the Map

for (let element of map) {
  console.log(element);
}

// Output:
// [ 'name', 'John' ]
// [ 'id', 11 ]

Print key value pairs

for (let [key, value] of map) {
  console.log(key + " - " + value);
}

// Output: 
// name - John
// id - 11

Print only keys of the Map

for (let key of map.keys()) {
  console.log(key);
}

// Output:
// name
// id

Print only values of the Map

for (let value of map.values()) {
  console.log(value);
}

// Output:
// John
// 11
2
  • 4
    Seems it's not compatible with JSON.stringify().
    – kenorb
    Aug 24, 2018 at 22:32
  • 2
    @kenorb this is ES6 , use JSON.stringify([...map]);
    – Robert
    May 28, 2021 at 9:14
22

In javascript a key value array is stored as an object. There are such things as arrays in javascript, but they are also somewhat considered objects still, check this guys answer - Why can I add named properties to an array as if it were an object?

Arrays are typically seen using square bracket syntax, and objects ("key=>value" arrays) using curly bracket syntax, though you can access and set object properties using square bracket syntax as Alexey Romanov has shown.

Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well.

Simple Array eg.

$(document).ready(function(){

    var countries = ['Canada','Us','France','Italy'];
    console.log('I am from '+countries[0]);
    $.each(countries, function(key, value) {
        console.log(key, value);
    });

});

Output -

0 "Canada"

1 "Us"

2 "France"

3 "Italy"

We see above that we can loop a numerical array using the jQuery.each function and access info outside of the loop using square brackets with numerical keys.

Simple Object (json)

$(document).ready(function(){

    var person = {
        name: "James",
        occupation: "programmer",
        height: {
            feet: 6,
            inches: 1
        },
    }

    console.log("My name is "+person.name+" and I am a "+person.height.feet+" ft "+person.height.inches+" "+person.occupation);

    $.each(person, function(key, value) {
        console.log(key, value);
    });

});

Output -

My name is James and I am a 6 ft 1 programmer

name James

occupation programmer

height Object {feet: 6, inches: 1}

In a language like php this would be considered a multidimensional array with key value pairs, or an array within an array. I'm assuming because you asked about how to loop through a key value array you would want to know how to get an object (key=>value array) like the person object above to have, let's say, more than one person.

Well, now that we know javascript arrays are used typically for numeric indexing and objects more flexibly for associative indexing, we will use them together to create an array of objects that we can loop through, like so -

JSON array (array of objects) -

$(document).ready(function(){

    var people = [
        {
            name: "James",
            occupation: "programmer",
            height: {
                feet: 6,
                inches: 1
            }
        }, {
            name: "Peter",
            occupation: "designer",
            height: {
                feet: 4,
                inches: 10
            }
        }, {
            name: "Joshua",
            occupation: "CEO",
            height: {
                feet: 5,
                inches: 11
            }
        }
    ];

    console.log("My name is "+people[2].name+" and I am a "+people[2].height.feet+" ft "+people[2].height.inches+" "+people[2].occupation+"\n");

    $.each(people, function(key, person) {
        console.log("My name is "+person.name+" and I am a "+person.height.feet+" ft "+person.height.inches+" "+person.occupation+"\n");
    });

});

Output -

My name is Joshua and I am a 5 ft 11 CEO

My name is James and I am a 6 ft 1 programmer

My name is Peter and I am a 4 ft 10 designer

My name is Joshua and I am a 5 ft 11 CEO

Note that outside the loop I have to use the square bracket syntax with a numeric key because this is now an numerically indexed array of objects, and of course inside the loop the numeric key is implied.

1
  • Well explained helped me fix an issue where i was building something to capture heights.
    – pranay
    Jun 7, 2020 at 11:44
13

Objects inside an array:

var cars = [
        { "id": 1, brand: "Ferrari" }
        , { "id": 2, brand: "Lotus" }
        , { "id": 3, brand: "Lamborghini" }
    ];
10

Simply do this

var key = "keyOne";
var obj = {};
obj[key] = someValue;
1
  • This is what helped me. A simple tweak and did the same in my <script> tag in HTML too and it worked. I was wondering why HTML doesn't understand if I don't declare a key var separately! Oct 7, 2020 at 20:58
1

I know its late but it might be helpful for those that want other ways. Another way array key=>values can be stored is by using an array method called map(); (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) you can use arrow function too

 
    var countries = ['Canada','Us','France','Italy'];  
// Arrow Function
countries.map((value, key) => key+ ' : ' + value );
// Anonomous Function
countries.map(function(value, key){
return key + " : " + value;
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.