如何按entityName分组对象数组,按规则处理color并合并details
实现方案
你可以通过Map分组+规则判定实现需求,步骤如下:
- 第一步用Map以
entityName为键缓存分组数据,每组同时记录所有出现过的color值和拼接后的details - 第二步遍历完所有原始数据后,按每组color的数量判定最终color取值:如果同组有2种及以上不同color则设为yellow,否则保留原color
- 第三步把Map缓存数据转为数组格式即为最终结果
完整实现代码如下:
function mergeGroup(data) { const groupMap = new Map() // 遍历原始数据做分组 for (const item of data) { const { entityName, color, details } = item if (groupMap.has(entityName)) { // 已有分组,更新数据 const group = groupMap.get(entityName) group.colorSet.add(color) group.details += ` ${details}` } else { // 新增分组 groupMap.set(entityName, { colorSet: new Set([color]), details: details }) } } // 转换为结果数组 return Array.from(groupMap.entries()).map(([entityName, group]) => { return { entityName, color: group.colorSet.size > 1 ? 'yellow' : Array.from(group.colorSet)[0], details: group.details } }) } // 测试示例 let data = [ {entityName: "Amazon", color: "red", details: "Hello"}, {entityName: "Amazon", color: "green", details: "World"}, {entityName: "Flipkart", color: "green", details: "1234567"} ] console.log(mergeGroup(data)) // 输出结果和预期一致
如果details的拼接规则不是用空格分隔,可以自行修改代码中拼接的符号。
内容的提问来源于stack exchange,提问作者Zahid Hussain
相关产品推荐
相关产品推荐

