如何合并对象数组中重复name键的关联值至单个数组?
嘿,这个需求我日常处理数据时经常碰到,给你分享两种实用的实现方案,完美匹配你的场景~
合并重复
name的对象并整合关联value数组 先明确下需求:把原数组中name重复的对象合并,每个name对应一个包含所有关联value的数组,还可以顺便给value去重(看你示例里有重复的weight value 3,应该也需要这个处理对吧?)
方案一:用reduce+对象映射(带value去重)
这是最常用的高效解法,代码简洁还能处理重复值:
let array = [ { name: "dimensions", value: "dimensions value 1" }, { name: "weight", value: "weight value 1" }, { name: "dimensions", value: "dimensions value 2" }, { name: "weight", value: "weight value 3" }, { name: "dimensions", value: "dimensions value 3" }, { name: "weight", value: "weight value 3" } ]; const mergedArray = Object.values(array.reduce((accumulator, currentItem) => { // 若当前name未在累加器中,初始化对应的结构 if (!accumulator[currentItem.name]) { accumulator[currentItem.name] = { name: currentItem.name, value: [] }; } // 避免重复添加相同的value if (!accumulator[currentItem.name].value.includes(currentItem.value)) { accumulator[currentItem.name].value.push(currentItem.value); } return accumulator; }, {})); console.log(mergedArray);
输出结果
[ { name: "dimensions", value: ["dimensions value 1", "dimensions value 2", "dimensions value 3"] }, { name: "weight", value: ["weight value 1", "weight value 3"] } ]
代码拆解
Array.reduce():遍历原数组,用一个临时对象(accumulator)来缓存每个name对应的整合结果- 每次遍历先检查当前
name是否已存在,不存在就初始化一个带空value数组的对象 - 用
Array.includes()判断当前value是否已存在,避免重复插入 - 最后用
Object.values()把临时对象的所有值提取成数组,就是我们要的最终结构
方案二:仅合并value(不去重)
如果你的需求里不需要给value去重,只想把所有关联值都整合,那可以简化代码:
const mergedArray = Object.values(array.reduce((accumulator, currentItem) => { // 初始化或复用已有结构 accumulator[currentItem.name] = accumulator[currentItem.name] || { name: currentItem.name, value: [] }; // 直接push,不做去重判断 accumulator[currentItem.name].value.push(currentItem.value); return accumulator; }, {}));
这样处理后,重复的weight value 3会保留两次,根据你的实际需求选择即可~
内容的提问来源于stack exchange,提问作者Hesan Aminiloo
相关产品推荐
相关产品推荐

