How to iterate over a JavaScript object?

后端 未结 18 1726
失恋的感觉
失恋的感觉 2020-11-21 22:52

I have an object in JavaScript:

{
    abc: \'...\',
    bca: \'...\',
    zzz: \'...\',
    xxx: \'...\',
    ccc: \'...\',
    // ...
}

I

18条回答
  •  星月不相逢
    2020-11-21 23:06

    Using Object.entries you do something like this.

     // array like object with random key ordering
     const anObj = { 100: 'a', 2: 'b', 7: 'c' };
     console.log(Object.entries(anObj)); // [ ['2', 'b'],['7', 'c'],['100', 'a'] ]
    

    The Object.entries() method returns an array of a given object's own enumerable property [key, value]

    So you can iterate over the Object and have key and value for each of the object and get something like this.

    const anObj = { 100: 'a', 2: 'b', 7: 'c' };
    Object.entries(anObj).map(obj => {
       const key   = obj[0];
       const value = obj[1];
    
       // do whatever you want with those values.
    });
    

    or like this

    // Or, using array extras
    Object.entries(obj).forEach(([key, value]) => {
      console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
    });
    

    For a reference have a look at the MDN docs for Object Entries

提交回复
热议问题