如何在JavaScript中按Person分组并合并Wants字段字符串?
JavaScript按Person分组合并Wants字段的方法
原始数组
let result = [{"Person": "Bob","Wants":"Shoes"}, {"Person": "Bob","Wants":"Socks"}, {"Person": "Sam","Wants":"Coffee"}, {"Person": "Tim","Wants":"Puppy"}, {"Person": "Sam","Wants":"Biscuit"}];
目标数组
let summary = [{"Person":"Bob","Wants":"Shoes, Socks"}, {"Person":"Sam","Wants":"Coffee, Biscuit"}, {"Person":"Tim","Wants":"Puppy"}];
实现方法
用Array.reduce()做分组是最直接的方案,配合Object.entries()和Array.map()就能转换成目标格式,代码逻辑清晰,适合新手理解:
let result = [{"Person": "Bob","Wants":"Shoes"}, {"Person": "Bob","Wants":"Socks"}, {"Person": "Sam","Wants":"Coffee"}, {"Person": "Tim","Wants":"Puppy"}, {"Person": "Sam","Wants":"Biscuit"}]; // 第一步:按Person分组,收集对应Wants到数组中 const groupedData = result.reduce((tempObj, item) => { // 如果当前Person还没在临时对象里,先初始化空数组 if (!tempObj[item.Person]) { tempObj[item.Person] = []; } // 把当前Wants添加到对应Person的数组里 tempObj[item.Person].push(item.Wants); return tempObj; }, {}); // 初始值是空对象,用来临时存分组结果 // 第二步:把分组对象转换成目标数组格式 const summary = Object.entries(groupedData).map(([personName, wantsList]) => ({ Person: personName, Wants: wantsList.join(', ') // 将数组转成逗号分隔的字符串 })); console.log(summary);
代码说明
reduce遍历原始数组时,用临时对象tempObj存储每个Person对应的Wants列表,避免重复创建Person条目。Object.entries()把分组对象拆成[Person名称, Wants数组]的键值对格式,方便后续转换。map遍历这些键值对,将其转换成目标的对象结构,join(', ')负责把数组中的Wants字符串合并成逗号分隔的格式。
内容的提问来源于stack exchange,提问作者High Plains Grifter
相关产品推荐
相关产品推荐

