【问题标题】:Looping through array of objects and return the key and value for each object遍历对象数组并返回每个对象的键和值
【发布时间】:2020-07-21 01:29:11
【问题描述】:

我有以下数组:

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

我有以下 React JSX 代码来循环遍历数组中的每个对象:

<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>

我得到了结果并且工作正常,但我的 IDE 通知我以下消息: 'for' statement doesn't loop为什么我会看到这条消息?

我还想知道,在我的示例案例中,使用 for...of 循环遍历对象条目并返回 JSX 代码是否是最好的方法,或者是否有其他更好的方法可以遵循。

【问题讨论】:

    标签: javascript arrays reactjs javascript-objects for-of-loop


    【解决方案1】:

    为什么我看到消息“'for' statement doesn't loop”?

    因为循环体中有一个无条件的return 语句,这导致循环永远不会超过第一次迭代。当然,鉴于您必须处理的奇怪数据格式,这有点像您想要的,但 linter 仍然抱怨它。在代码中表达这一点的更好方法可能是

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

    如果您绝对确定每个对象将具有至少一个属性,则可以省略 if 条件,并且不关心如果不存在则引发异常:

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

    (理想的解决方案当然是更改cuisines 的格式,例如改为Map 而不是数组)

    【讨论】:

    • 感谢您的澄清。两种解决方案都运行良好,我也会尝试使用 Map。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 2021-12-16
    • 2011-10-12
    • 2021-10-05
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多