1

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.

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the clarification. Both solutions are working fine and I'll give the Map a try as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.