351

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.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Ali
  • 261,656
  • 265
  • 575
  • 769

7 Answers7

577

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.

Community
  • 1
  • 1
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • 29
    If your browser supports it (IE9 and up), it is safer to create the empty object first with [`var foo = Object.create(null)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) 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`. – Rory O'Kane Aug 12 '14 at 03:00
  • 1
    @RoryO'Kane you could use hasownproperty to get around that. –  Apr 22 '16 at 10:11
  • 7
    @DaMaxContent you could also turn right by turning left three times. – coderatchet Jul 08 '16 at 03:39
  • 1
    @thenaglecode Sometimes left 3 times works. Imagine if you couldn't turn right? Or you had to do it more than once? –  Jul 08 '16 at 05:26
  • 1
    But perhaps OP wanted an array since objects wont keep the order of items consistently across browser implementations? – trainoasis Apr 22 '20 at 09:31
  • Was just about to comment the same thing @trainoasis mentioned, items are NOT guaranteed to be delivered in a "for in" loop in the same order as they were declared – insaner Jan 26 '22 at 01:57
  • @alexeyRomanov how would you rename id1 to id99 ? – strix25 Sep 20 '22 at 10:26
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
Blixt
  • 49,547
  • 13
  • 120
  • 153
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
Mukesh Chapagain
  • 25,063
  • 15
  • 119
  • 120
21

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.

kiko carisse
  • 1,634
  • 19
  • 21
12

Objects inside an array:

var cars = [
        { "id": 1, brand: "Ferrari" }
        , { "id": 2, brand: "Lotus" }
        , { "id": 3, brand: "Lamborghini" }
    ];
tedi
  • 6,350
  • 5
  • 52
  • 67
10

Simply do this

var key = "keyOne";
var obj = {};
obj[key] = someValue;
Vineeth Sai
  • 3,389
  • 7
  • 23
  • 34
Faizan Qureshi
  • 101
  • 2
  • 5
  • This is what helped me. A simple tweak and did the same in my – Arjun Kalidas Oct 07 '20 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;
});
krialex21
  • 431
  • 4
  • 5