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

如何在TypeScript中合并两个内置Record类型并实现同键值数组合并去重

TypeScript合并带数组值的Record类型实现方案

实现思路

  • 提取两个Record的所有唯一key,保证不会遗漏任何一侧的键
  • 对每个key,分别取出两个Record中对应的数组,不存在则默认是空数组
  • 合并两个数组后通过Set去重,再转回数组即可,Set会保留元素插入顺序,和题目要求的输出顺序完全匹配

针对题目场景的实现代码

// 题目给出的原始变量
const dictionary1: Record<string, string[]> = {
  'fruits': ['apple','banana', 'cherry'],
  'vegetables': ['cucumber','onion']
};

const dictionary2: Record<string, string[]> = {
  'fruits': ['apple','banana', 'orange', 'pear'],
  'vegetables': ['cucumber','corn'],
  'beverages': ['soda']
};

// 合并逻辑
const mergedDictionary: Record<string, string[]> = {};
// 收集两个对象的所有唯一key
const allKeys = new Set([...Object.keys(dictionary1), ...Object.keys(dictionary2)]);

for (const key of allKeys) {
  // 拼接数组后去重
  const mergedArr = [...new Set([
    ...(dictionary1[key] || []),
    ...(dictionary2[key] || [])
  ])];
  mergedDictionary[key] = mergedArr;
}

可复用的泛型实现

如果需要在多个场景复用该合并逻辑,可封装为通用泛型函数,支持任意值为数组的Record类型:

function mergeRecordWithArrayValues<T extends string, U>(
  recordA: Record<T, U[]>,
  recordB: Record<T, U[]>
): Record<T, U[]> {
  const merged: Record<T, U[]> = {} as Record<T, U[]>;
  const allKeys = new Set([...Object.keys(recordA), ...Object.keys(recordB)]) as Set<T>;

  for (const key of allKeys) {
    merged[key] = [...new Set([
      ...(recordA[key] || []),
      ...(recordB[key] || [])
    ])];
  }
  return merged;
}

// 调用示例
const mergedDictionary = mergeRecordWithArrayValues(dictionary1, dictionary2);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:36:03