如何按id关联动态合并两个JSON对象数组并重构数据结构
双JSON数据按关联键合并落地方案
核心匹配规则落地逻辑:
- 主表为JSON Data1,关联匹配字段为
id - 副表为JSON Data2,关联匹配字段为
prodsub_id - 匹配命中后,将副表的
narra_title、narra_content、offer三个字段挂载到主表对应记录下 - 性能优化:先将副表转换为以关联键为key的哈希映射,避免双层循环带来的O(n²)性能损耗,千条以上数据场景下性能提升明显
JavaScript 实现(前端/Node.js环境通用)
function mergeJsonData(data1, data2) { // 构建副表映射 const data2Index = new Map() for (const item of data2) { // 同关联键对应多条副表记录时可自行调整存储逻辑,此处默认取第一条 if (!data2Index.has(item.prodsub_id)) { data2Index.set(item.prodsub_id, item) } } // 遍历主表合并字段 return data1.map(mainItem => { const matched = data2Index.get(mainItem.id) return { ...mainItem, narra_title: matched?.narra_title ?? '', narra_content: matched?.narra_content ?? '', offer: matched?.offer ?? null } }) } // 调用方式:const result = mergeJsonData(你的Data1数组, 你的Data2数组)
Python 实现(后端/数据处理脚本通用)
def merge_json_data(data1: list[dict], data2: list[dict]) -> list[dict]: # 构建副表映射 data2_index = {} for sub_item in data2: sub_id = sub_item.get("prodsub_id") if sub_id not in data2_index: data2_index[sub_id] = sub_item merged_res = [] for main_item in data1: main_id = main_item.get("id") matched_item = data2_index.get(main_id) # 拷贝原始主表记录,避免修改源数据 current = main_item.copy() current["narra_title"] = matched_item.get("narra_title", "") if matched_item else "" current["narra_content"] = matched_item.get("narra_content", "") if matched_item else "" current["offer"] = matched_item.get("offer") if matched_item else None merged_res.append(current) return merged_res # 调用示例: # import json # with open("data1.json", "r", encoding="utf-8") as f: d1 = json.load(f) # with open("data2.json", "r", encoding="utf-8") as f: d2 = json.load(f) # final_data = merge_json_data(d1, d2)
自定义调整说明
- 若单个
prodsub_id对应多条副表记录,可将映射表的value改为数组结构,合并时按需处理多记录挂载逻辑 - 无匹配记录时的默认值(空字符串、null)可根据业务要求自行替换
- 若需要保留副表其他字段,直接在合并逻辑里加对应字段的取值即可
内容的提问来源于stack exchange,提问作者DarkChocolate Reborn
相关产品推荐
相关产品推荐

