React中遍历对象数组如何不受顺序影响按属性匹配渲染
解决方案
核心逻辑是先将顺序不固定的对象数组转换为以atr1值为键、atr2值为值的映射表,后续直接通过固定键名取值,完全不受原数组元素排列顺序的影响。
- 移除原有遍历
eList渲染整个表格的错误逻辑:该写法会为数组中每一个对象都生成一个完整表格,不符合预期,表格结构固定仅需渲染一次。 - 用
reduce方法预处理eList生成映射对象,无论原数组内元素顺序如何调整,都能精准取到AA/BB/CC对应的数值。
修正后的可直接运行代码如下:
const eList = ecom[0].esat.ttl // 预处理生成键值映射,和原数组元素顺序无关 const attrValueMap = eList.reduce((res, currentItem) => { res[currentItem.atr1] = currentItem.atr2 return res }, {}) return ( <table className="greyGridTable"> <tbody> <tr> <td>AA</td> <td>{attrValueMap.AA}</td> </tr> <tr> <td>BB</td> <td>{attrValueMap.BB}</td> </tr> <tr> <td>CC</td> <td>{attrValueMap.CC}</td> </tr> </tbody> </table> )
如果后续需要扩展匹配项、或者希望减少重复代码,可以提前定义固定渲染顺序的键数组,遍历该固定数组渲染表格行即可,同样不会受原数组顺序干扰:
const eList = ecom[0].esat.ttl const attrValueMap = eList.reduce((res, currentItem) => { res[currentItem.atr1] = currentItem.atr2 return res }, {}) // 自定义固定渲染顺序 const renderOrder = ['AA', 'BB', 'CC'] return ( <table className="greyGridTable"> <tbody> {renderOrder.map(key => ( <tr key={key}> <td>{key}</td> <td>{attrValueMap[key]}</td> </tr> ))} </tbody> </table> )
注意:如果使用React框架,
class属性需要写为className避免语法警告,原生HTML场景保留class即可。
内容的提问来源于stack exchange,提问作者R9102
相关产品推荐
相关产品推荐

