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

基于关联键实现JSON数组动态左连接合并(无需显式指定字段)

高效实现动态字段的左连接合并方案

核心思路

要实现动态字段的左连接且保证效率,核心是先构建定价数据的哈希映射表,将单条数据的查找时间从O(n)降到O(1),整体时间复杂度控制在O(n+m)(n为产品数组长度,m为定价数组长度),远优于嵌套循环的O(n*m)。

实现代码

假设通过useFetch获取到的原始数据结构如下:

const fetchedData = {
  "Product Info": [
    { "Part Num": "P001", "Product Name": "Laptop", "Brand": "A" },
    { "Part Num": "P002", "Product Name": "Phone", "Brand": "B" },
    // ...更多产品数据
  ],
  "Company Pricing": [
    { "Pricing Reference Name": "P001", "Unit Price": 999, "Discount": 0.1 },
    { "Pricing Reference Name": "P003", "Unit Price": 599, "Discount": 0.05 },
    // ...更多定价数据
  ]
};

实现左连接的函数:

function leftJoinProductAndPricing(data) {
  // 构建定价数据的哈希映射:以Pricing Reference Name为键,存储整条定价对象
  const pricingMap = new Map();
  data["Company Pricing"].forEach(pricing => {
    const key = pricing["Pricing Reference Name"];
    pricingMap.set(key, pricing);
  });

  // 遍历产品数组,动态合并匹配的定价字段
  return data["Product Info"].map(product => {
    const matchingPricing = pricingMap.get(product["Part Num"]) || {};
    // 用展开运算符合并所有字段,无需显式指定
    return { ...product, ...matchingPricing };
  });
}

// 使用示例
const mergedData = leftJoinProductAndPricing(fetchedData);

关键说明

  • 动态字段适配:通过...product和...matchingPricing展开所有属性,无论两个数组的字段新增或删除,都能自动完成合并,完全不需要硬编码字段名。
  • 左连接保证:即使某个产品没有匹配的定价数据(比如示例中的P002),也会完整保留产品的所有字段,定价字段会以空对象形式合并(即不存在对应键)。
  • 高效性:哈希映射表的构建是O(m),遍历产品数组是O(n),整体为线性时间复杂度,处理大数据量时优势明显。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 23:30:07