How to iterate over a JavaScript object?

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

I have an object in JavaScript:

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

I

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

    For object iteration we usually use a for..in loop. This structure will loop through all enumerable properties, including ones who are inherited via prototypal inheritance. For example:

    let obj = {
      prop1: '1',
      prop2: '2'
    }
    
    for(let el in obj) {
      console.log(el);
      console.log(obj[el]);
    }

    However, for..in will loop over all enumerable elements and this will not able us to split the iteration in chunks. To achieve this we can use the built in Object.keys() function to retrieve all the keys of an object in an array. We then can split up the iteration into multiple for loops and access the properties using the keys array. For example:

    let obj = {
      prop1: '1',
      prop2: '2',
      prop3: '3',
      prop4: '4',
    };
    
    const keys = Object.keys(obj);
    console.log(keys);
    
    
    for (let i = 0; i < 2; i++) {
      console.log(obj[keys[i]]);
    }
    
    
    for (let i = 2; i < 4; i++) {
      console.log(obj[keys[i]]);
    }

提交回复
热议问题