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

如何合并对象数组中同hash的values属性(不使用扩展运算符)

合并数组中同hash对象的values属性

需求:处理给定的对象数组,当数组内对象的hash值相同时,合并所有该hash对应的values属性,并将所有同hash对象的values替换为合并后的结果,代码中禁止使用扩展运算符。

输入数组:

[{"hash": "12345","values": [1,2,3]},{"hash": "12345","values": []},{"hash": "12345","values": [4]},{"hash": "6789","values": [9]},{"hash": "6789","values": [1]}]

期望输出数组:

[{"hash": "12345","values": [1,2,3,4]},{"hash": "12345","values": [1,2,3,4]},{"hash": "12345","values": [1,2,3,4]},{"hash": "6789","values": [1,9]},{"hash": "6789","values": [1,9]}]

解决方案代码

// 收集每个hash对应的合并后values
const hashMap = {};
const inputArr = [{"hash": "12345","values": [1,2,3]},{"hash": "12345","values": []},{"hash": "12345","values": [4]},{"hash": "6789","values": [9]},{"hash": "6789","values": [1]}];

// 遍历输入数组,构建hash映射表
for (let i = 0; i < inputArr.length; i++) {
  const current = inputArr[i];
  if (!hashMap[current.hash]) {
    hashMap[current.hash] = [];
  }
  // 用concat合并数组,避免扩展运算符
  hashMap[current.hash] = hashMap[current.hash].concat(current.values);
}

// 生成结果数组,替换每个对象的values
const resultArr = [];
for (let i = 0; i < inputArr.length; i++) {
  const current = inputArr[i];
  // 用Object.assign复制原对象,避免修改原数据
  const newObj = Object.assign({}, current);
  newObj.values = hashMap[current.hash];
  resultArr.push(newObj);
}

console.log(resultArr);

代码说明

  1. 构建hash映射表:遍历输入数组,用对象hashMap存储每个hash对应的合并后values,通过concat方法合并数组,完全避开扩展运算符。
  2. 生成结果数组:再次遍历原数组,为每个对象创建副本(避免修改原数据),将其values替换为hashMap中对应的值,最后存入结果数组。
  3. 空数组会被concat自动忽略,不会影响最终合并结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 19:23:15