You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用React JS按id合并对象数组并将结果渲染为表格的实现问题

React 实现按id合并对象数组并渲染表格方案

1. 数组合并核心逻辑

要实现按id匹配合并同id对象的所有属性,可以借助对象映射实现,避免双重循环降低性能,核心逻辑如下:

// 示例数组
const array1 = [
  {id: 1, event: 'party', oldcity: 'Singapore'},
  {id: 2, event: 'fest', oldcity: 'Paris'}
]
const array2 = [
  {id: 1, event: 'party', newcity: 'bombay'},
  {id: 2, event: 'fest', newcity: 'madras'}
]

// 合并逻辑
const map = {}
// 先把array1的元素按id存入映射
array1.forEach(item => {
  map[item.id] = {...item}
})
// 遍历array2合并同id属性
array2.forEach(item => {
  if (map[item.id]) {
    // 已有同id项,合并属性
    map[item.id] = {...map[item.id], ...item}
  } else {
    // 无同id项直接新增(可根据业务需求选择是否保留该逻辑)
    map[item.id] = {...item}
  }
})
// 转成数组得到目标结果
const mergeArray = Object.values(map)

注:如果属性出现冲突,array2的属性会覆盖array1的同名属性,要调整优先级可交换两个数组的遍历顺序。

2. 完整React组件示例

import React from 'react'

const MergeTable = () => {
  const array1 = [
    {id: 1, event: 'party', oldcity: 'Singapore'},
    {id: 2, event: 'fest', oldcity: 'Paris'}
  ]
  const array2 = [
    {id: 1, event: 'party', newcity: 'bombay'},
    {id: 2, event: 'fest', newcity: 'madras'}
  ]

  // 合并数组
  const getMergeArray = () => {
    const map = {}
    array1.forEach(item => {
      map[item.id] = {...item}
    })
    array2.forEach(item => {
      map[item.id] = map[item.id] ? {...map[item.id], ...item} : {...item}
    })
    return Object.values(map)
  }

  const mergeArray = getMergeArray()

  return (
    <table border={1} cellPadding={8} cellSpacing={0}>
      <thead>
        <tr>
          <th>id</th>
          <th>event</th>
          <th>oldcity</th>
          <th>newcity</th>
        </tr>
      </thead>
      <tbody>
        {mergeArray.map(item => (
          <tr key={item.id}>
            <td>{item.id}</td>
            <td>{item.event}</td>
            <td>{item.oldcity}</td>
            <td>{item.newcity}</td>
          </tr>
        ))}
      </tbody>
    </table>
  )
}

export default MergeTable

实现效果

最终渲染的表格会展示四列数据,每行对应同一个id的完整合并属性,和预期的合并结果完全一致。

内容的提问来源于stack exchange,提问作者Raghu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 08:54:03