How to iterate over a JavaScript object?

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

I have an object in JavaScript:

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

I

18条回答
  •  没有蜡笔的小新
    2020-11-21 23:23

    If you have a simple object you can iterate through it using the following code:

    let myObj = {
      abc: '...',
      bca: '...',
      zzz: '...',
      xxx: '...',
      ccc: '...',
      // ...
    };
    
    let objKeys = Object.keys(myObj);
    
    //Now we can use objKeys to iterate over myObj
    
    for (item of objKeys) {
      //this will print out the keys
      console.log('key:', item);
      
      //this will print out the values 
      console.log('value:', myObj[item]);
    }

    If you have a nested object you can iterate through it using the following code:

    let b = {
      one: {
        a: 1,
        b: 2,
        c: 3
      },
      two: {
        a: 4,
        b: 5,
        c: 6
      },
      three: {
        a: 7,
        b: 8,
        c: 9
      }
    };
    
    let myKeys = Object.keys(b);
    
    for (item of myKeys) {
      //print the key
      console.log('Key', item)
      
      //print the value (which will be another object)
      console.log('Value', b[item])
      
      //print the nested value
      console.log('Nested value', b[item]['a'])
    }

    If you have array of objects you can iterate through it using the following code:

    let c = [
    {
      a: 1,
      b: 2
    },
    {
      a: 3,
      b: 4
    }
    ];
    
    for(item of c){
    //print the whole object individually 
    console.log('object', item);
    
    //print the value inside the object
    console.log('value', item['a']);
    }

提交回复
热议问题