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

TypeScript下基于公共id键合并不同结构的对象数组

实现方案

你可以先将远端用户数组预处理为 id 为键的映射结构,再遍历本地用户数组完成合并,整体时间复杂度为 O(n+m),数据量较大时也能保持较好的性能,且不会修改原始数组。

基础 JS 实现(兼容现代浏览器/Node 环境)

// 预处理为id-timestamp映射,后续查询时间复杂度O(1)
const remoteUserMap = new Map(remoteUsers.map(user => [user.id, user.timestamp]))

// 遍历本地数组合并数据
const allUsers = localUsers.map(localUser => {
  return {
    ...localUser,
    // 空值合并运算符避免合法空字符串被误覆盖
    timestamp: remoteUserMap.get(localUser.id) ?? null
  }
})

兼容旧环境实现(不支持Map/扩展运算符场景)

var remoteUserMap = {}
for (var i = 0; i < remoteUsers.length; i++) {
  var remote = remoteUsers[i]
  remoteUserMap[remote.id] = remote.timestamp
}

var allUsers = []
for (var j = 0; j < localUsers.length; j++) {
  var local = localUsers[j]
  var merged = Object.assign({}, local)
  merged.timestamp = remoteUserMap[local.id] || null
  allUsers.push(merged)
}

TypeScript 带类型实现

// 定义类型保证类型安全
type LocalUser = {
  firstName: string
  lastName: string
  id: string
}

type RemoteUser = {
  id: string
  timestamp: string
}

type MergedUser = LocalUser & {
  timestamp: string | null
}

const remoteUserMap = new Map<string, string>(
  remoteUsers.map((user: RemoteUser) => [user.id, user.timestamp])
)

const allUsers: MergedUser[] = localUsers.map((localUser: LocalUser) => {
  return {
    ...localUser,
    timestamp: remoteUserMap.get(localUser.id) ?? null
  }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:57:03