如何使用reduce合并数组中同键的对象数组元素
合并数组内对象的数组属性
问题场景
现有如下结构的数组:
[ { "AREA": [ "EMAC" ], "SUPER_REGION": [ "South East Europe Region", "East Europe Region" ] }, { "AREA": [ "CCA" ], "SUPER_REGION": [ "Taiwan", "China Hong Kong" ] } ]
需要将数组中每个对象的对应数组属性合并,得到如下结果:
{ "AREA": [ "EMAC","CCA" ], "SUPER_REGION": [ "South East Europe Region", "East Europe Region", "Taiwan", "China Hong Kong" ] }
当前使用的reduce代码会将数组元素拼接成字符串,无法实现需求:
let sum = finalval.reduce(function (accumulator, { AREA, SUPER_REGION }) { accumulator["AREA"] += AREA; return accumulator; }, {});
解决方案
问题核心在于误用了字符串拼接运算符+=,正确的做法是针对数组属性执行数组合并操作,以下是几种可行方案:
方案1:使用concat合并数组
通过concat方法将当前对象的数组属性合并到累加器的对应数组中,同时处理初始值为undefined的情况:
let sum = finalval.reduce((accumulator, { AREA, SUPER_REGION }) => { accumulator.AREA = (accumulator.AREA || []).concat(AREA); accumulator.SUPER_REGION = (accumulator.SUPER_REGION || []).concat(SUPER_REGION); return accumulator; }, {});
方案2:使用push配合扩展运算符
直接修改累加器的数组,通过扩展运算符将当前数组的元素逐个添加进去,性能更优:
let sum = finalval.reduce((accumulator, { AREA, SUPER_REGION }) => { // 初始化对应属性为数组(首次循环时执行) if (!accumulator.AREA) accumulator.AREA = []; if (!accumulator.SUPER_REGION) accumulator.SUPER_REGION = []; accumulator.AREA.push(...AREA); accumulator.SUPER_REGION.push(...SUPER_REGION); return accumulator; }, {});
方案3:通用化处理(适配任意属性)
如果对象的属性不固定,可以通过遍历当前对象的所有属性来实现通用合并:
let sum = finalval.reduce((accumulator, currentObj) => { Object.keys(currentObj).forEach(key => { accumulator[key] = (accumulator[key] || []).concat(currentObj[key]); }); return accumulator; }, {});
内容的提问来源于stack exchange,提问作者Divakar R
相关产品推荐
相关产品推荐

