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

JavaScript如何按条件匹配两个数组生成指定结构新数组

JavaScript 实现方案

核心逻辑是按array1.id === array2.toyId的关联规则做数据组装,保留array1的name字段,将匹配到的array2项的label、type字段归集到newdata子数组。

写法1:易读基础版(适合数据量小的场景)

直接遍历第一个数组,对每个元素筛选第二个数组里的匹配项,做字段裁剪后组装:

const Array3 = Array1.map(item1 => {
  // 筛选匹配的array2项
  const matchItems = Array2.filter(item2 => item2.toyId === item1.id)
  // 提取需要的label、type字段
  const newdata = matchItems.map(({ label, type }) => ({ label, type }))
  return {
    name: item1.name,
    newdata
  }
})

注:你示例中Array1第一项name写的是arujn,目标结果里是arjun,属于笔误,上述代码会直接取原始数组的name值,如有需要可自行修正原始数据的拼写。

写法2:高性能版(适合数据量较大的场景)

先把Array2按toyId做一次分组预处理,避免每次遍历Array1都全量扫描Array2,时间复杂度从O(n*m)降到O(n+m):

// 先按toyId预分组array2的数据
const toyGroup = new Map()
for (const item2 of Array2) {
  if (!toyGroup.has(item2.toyId)) {
    toyGroup.set(item2.toyId, [])
  }
  toyGroup.get(item2.toyId).push({
    label: item2.label,
    type: item2.type
  })
}
// 遍历array1直接取预分组好的数据组装
const Array3 = Array1.map(item1 => ({
  name: item1.name,
  newdata: toyGroup.get(item1.id) || []
}))

两种写法最终输出的结构都和你要求的目标Array3完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 09:06:26