Traverse the object array in js and get the corresponding attribute value of the object

There are many ways to traverse an array of objects in JavaScript. The following are four common methods: for​loop, for...of​loop, forEach​method and map​method, while traversing, access the properties of the object to get the corresponding value.

  1. Loopfor :

    const objArray = [
      {
          
           id: 1, name: 'Alice' },
      {
          
           id: 2, name: 'Bob' },
      {
          
           id: 3, name: 'Charlie' },
    ];
    
    for (let i = 0; i < objArray.length; i++) {
          
          
      const obj = objArray[i];
      console.log(obj.id, obj.name);
    }
    
  2. Loopfor...of :

    const objArray = [
      {
          
           id: 1, name: 'Alice' },
      {
          
           id: 2, name: 'Bob' },
      {
          
           id: 3, name: 'Charlie' },
    ];
    
    for (const obj of objArray) {
          
          
      console.log(obj.id, obj.name);
    }
    
    
  3. ​​MethodforEach :

    const objArray = [
      {
          
           id: 1, name: 'Alice' },
      {
          
           id: 2, name: 'Bob' },
      {
          
           id: 3, name: 'Charlie' },
    ];
    
    objArray.forEach((obj) => {
          
          
      console.log(obj.id, obj.name);
    });
    
  4. ​​​​Methodmap (usually used to create a new array, but can also be used to iterate):

    const objArray = [
      {
          
           id: 1, name: 'Alice' },
      {
          
           id: 2, name: 'Bob' },
      {
          
           id: 3, name: 'Charlie' },
    ];
    
    objArray.map((obj) => {
          
          
      console.log(obj.id, obj.name);
      return obj;
    });
    

All of the above methods can realize the extraction of property values ​​in the object while traversing the object array.

Guess you like

Origin blog.csdn.net/qq_46034741/article/details/130084577
Recommended