Search code examples
javascriptreactjsecmascript-6destructuring

ES6 - Destructuring and For of Loop only returns first object


I have a react app looping through the following object:

const topics = [
  {name: 'Mon', color: 'blue', id: 1},
  {name: 'Tue', color: 'red', id: 2},
  {name: 'Wed', color: 'pink', id: 3},
]

I'm trying to destructure and loop through the object via for of loop inside my functional component

 export const Data = () => {
       for (let {name, color, id} of topics) {
           console.log(name, color, id) //Only first iteration is outputted
               return (
                <div key={id}>
                    <div>{name}</div>
                    <div>{color}</div>
                </div>  
               )                                               
       }
    }

I'm only getting 1, Mon, blue What am I missing? Is this related to a return or render?


Solution

  • For of Loop only returns first object, Why?

    Because you are using return statement inside for...of body, and that is breaking the loop and returning the result. Remove the return and check it will print all the values.

    Check this snippet:

    const topics = [
      {name: 'Mon', color: 'blue', id: 1},
      {name: 'Tue', color: 'red', id: 2},
      {name: 'Wed', color: 'pink', id: 3},
    ]
    
    
    for (let {name, color, id} of topics) {
       console.log(name, color, id);                       
    }

    To render all the data use #array.map instead of for...of loop, write it like this:

    export const Data = () => (
        <div>
            {
                topics.map( ({ name, color, id }) => {
                    return (
                        <div key={id}>
                            <div>{name}</div>
                            <div>{color}</div>
                        </div>  
                    )
                })                                               
            }
        </div>
    )