How to iterate (keys, values) in javascript?

前端 未结 10 2727
孤街浪徒
孤街浪徒 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 10:08

    The Object.entries() method has been specified in ES2017 (and is supported in all modern browsers):

    for (const [ key, value ] of Object.entries(dictionary)) {
        // do something with `key` and `value`
    }
    

    Explanation:

    • Object.entries() takes an object like { a: 1, b: 2, c: 3 } and turns it into an array of key-value pairs: [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ].

    • With for ... of we can loop over the entries of the so created array.

    • Since we are guaranteed that each of the so iterated array items is itself a two-entry array, we can use destructuring to directly assign variables key and value to its first and second item.

提交回复
热议问题