How to iterate (keys, values) in javascript?

前端 未结 10 2726
孤街浪徒
孤街浪徒 2020-11-27 09:23

I have a dictionary that has the format of

dictionary = {0: {object}, 1:{object}, 2:{object}}

How can I iterate through this dictionary by

10条回答
  •  盖世英雄少女心
    2020-11-27 09:58

    tl;dr

    1. In ECMAScript 5, it is not possible.
    2. In ECMAScript 2015, it is possible with Maps.
    3. In ECMAScript 2017, it would be readily available.

    ECMAScript 5:

    No, its not possible with objects.

    You should either iterate with for..in, or Object.keys, like this

    for (var key in dictionary) {
        // check if the property/key is defined in the object itself, not in parent
        if (dictionary.hasOwnProperty(key)) {           
            console.log(key, dictionary[key]);
        }
    }
    

    Note: The if condition above is necessary, only if you want to iterate the properties which are dictionary object's very own. Because for..in will iterate through all the inherited enumerable properties.

    Or

    Object.keys(dictionary).forEach(function(key) {
        console.log(key, dictionary[key]);
    });
    

    ECMAScript 2015

    In ECMAScript 2015, you can use Map objects and iterate them with Map.prototype.entries. Quoting example from that page,

    var myMap = new Map();
    myMap.set("0", "foo");
    myMap.set(1, "bar");
    myMap.set({}, "baz");
    
    var mapIter = myMap.entries();
    
    console.log(mapIter.next().value); // ["0", "foo"]
    console.log(mapIter.next().value); // [1, "bar"]
    console.log(mapIter.next().value); // [Object, "baz"]
    

    Or iterate with for..of, like this

    'use strict';
    
    var myMap = new Map();
    myMap.set("0", "foo");
    myMap.set(1, "bar");
    myMap.set({}, "baz");
    
    for (const entry of myMap.entries()) {
      console.log(entry);
    }
    

    Output

    [ '0', 'foo' ]
    [ 1, 'bar' ]
    [ {}, 'baz' ]
    

    Or

    for (const [key, value] of myMap.entries()) {
      console.log(key, value);
    }
    

    Output

    0 foo
    1 bar
    {} baz
    

    ECMAScript 2017

    ECMAScript 2017 would introduce a new function Object.entries. You can use this to iterate the object as you wanted.

    'use strict';
    
    const object = {'a': 1, 'b': 2, 'c' : 3};
    for (const [key, value] of Object.entries(object)) {
      console.log(key, value);
    }
    

    Output

    a 1
    b 2
    c 3
    

提交回复
热议问题