Search code examples
javascriptarraysreactjsjavascript-objectsfor-of-loop

Looping through array of objects and return the key and value for each object


I have the following array:

const cuisines = [
   { african: "African" },
   { american: "American" },
   { arabian: "Arabian" },
   { argentine: "Argentine" },
   { asian: "Asian" },
   { asian_fusion: "Asian Fusion" },
   { australian: "Australian" },
   { austrian: "Austrian" },
   { bbq: "BBQ" },
   { bakery: "Bakery" }
]

and I have the following React JSX code to loop through each object in the array:

<select name="cuisines" id="cuisines" size={10} multiple className="form-control" onChange={e => handleMultiple('cuisines', e)}>
   {cuisines.map((cuisine, index) => {
      for (let [key, value] of Object.entries(cuisine)) {
         return <option key={index} value={key}>{value}</option>
      }
   })}
</select>

I'm getting the results and working fine but my IDE is informing me the following message: 'for' statement doesn't loop why I see this message?

enter image description here

Also I'm wondering if using for...of to loop through the object entries and return JSX code is the best approach in my example case or if there are any other approach that I can follow which is better.


Solution

  • Why I see the message "'for' statement doesn't loop"?

    Because you have an unconditional return statement inside the loop body, which causes the loop to never advance beyond the first iteration. Sure, this is kinda what you want given the weird data format you have to deal with, but the linter still complains about it. A better way to express this in code might be

    const entries = Object.entries(cuisine);
    if (entries.length) {
        const [key, value] = entries[0];
        return <option key={index} value={key}>{value}</option>
    }
    

    You can omit the if condition if you are absolutely certain that each object will have at least one property, and don't care about exceptions being raised if they don't:

    const [key, value] = Object.entries(cuisine)[0];
    return <option key={index} value={key}>{value}</option>
    

    (The ideal solution would of course be to change the format of cuisines, e.g. to a Map instead of an array)