How to iterate over a JavaScript object?

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

I have an object in JavaScript:

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

I

18条回答
  •  长发绾君心
    2020-11-21 23:12

    For most objects, use for .. in :

    for (let key in yourobject) {
      console.log(key, yourobject[key]);
    }
    

    With ES6, if you need both keys and values simultaneously, do

    for (let [key, value] of Object.entries(yourobject)) {
        console.log(key, value);
    }
    

    To avoid logging inherited properties, check with hasOwnProperty :

    for (let key in yourobject) {
       if (yourobject.hasOwnProperty(key)) {
          console.log(key, yourobject[key]);
       }
    }
    

    You don't need to check hasOwnProperty when iterating on keys if you're using a simple object (for example one you made yourself with {}).

    This MDN documentation explains more generally how to deal with objects and their properties.

    If you want to do it "in chunks", the best is to extract the keys in an array. As the order isn't guaranteed, this is the proper way. In modern browsers, you can use

    let keys = Object.keys(yourobject);
    

    To be more compatible, you'd better do this :

     let keys = [];
     for (let key in yourobject) {      
         if (yourobject.hasOwnProperty(key)) keys.push(key);
     }
    

    Then you can iterate on your properties by index: yourobject[keys[i]] :

    for (let i=300; i < keys.length && i < 600; i++) { 
       console.log(keys[i], yourobject[keys[i]]);
    }
    

提交回复
热议问题