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

如何基于嵌套对象键值合并两个JavaScript对象数组

实现方案

核心思路

  • 预先构建二级查找映射表,减少重复遍历开销:
    • 一级映射关联属性id和该id下的所有属性配置
    • 二级映射关联属性值和对应的完整属性对象
  • 遍历变体数组替换值即可完成合并

完整代码

const variants = [{
    "name": "Name 1",
    "variationValues": {
        "P00003": "mappedValue1",
        "P00004": "mappedValue4",
    }
}, {
    "name": "Name 2",
    "variationValues": {
        "P00003": "mappedValue2"
    }
}, {
    "name": "Name 3",
    "variationValues": {
        "P00003": "mappedValue3"
    }
}]

const variationAttributes = [{
    "id": "P00003",
    "name": "Variant Name",
    "attributes": [{
        "name": "Variant Name 1",
        "description": "Variant Description 1",
        "attribute": "mappedValue1"
    }, {
        "name": "Variant Name 2",
        "description": "Variant Description 2",
        "attribute": "mappedValue2"
    }, {
        "name": "Variant Name 3",
        "description": "Variant Description 3",
        "attribute": "mappedValue3"
    }, {
        "name": "Variant Name 4",
        "description": "Variant Description 4",
        "attribute": "mappedValue4"
    }]
}, {
    "id": "P00004",
    "name": "Variant Name",
    "attributes": [{
        "name": "Variant Name 4",
        "description": "Variant Description 4",
        "attribute": "mappedValue4"
    }]
}]

// 构建二级查找映射
const attrMap = variationAttributes.reduce((result, curr) => {
  const valueMap = new Map(curr.attributes.map(item => [item.attribute, item]))
  result.set(curr.id, valueMap)
  return result
}, new Map())

// 处理变体数据
const handledVariants = variants.map(item => {
  const newVariationValues = Object.entries(item.variationValues).reduce((values, [attrId, attrVal]) => {
    values[attrId] = attrMap.get(attrId)?.get(attrVal) ?? attrVal
    return values
  }, {})
  return { ...item, variationValues: newVariationValues }
})

// 组装为要求的输出格式
const result = [{ variants: handledVariants }]

console.log(result)

边界说明

代码中使用了可选链?.和空值合并运算符??做兼容,当出现id或者属性值匹配不到的情况时,会保留原有字符串值,不会抛出异常,你可以根据实际业务需求调整匹配失败的处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 11:57:00