如何按属性对数组对象进行分组,按oldStockBooks.name统计同名书籍数量
按oldStockBooks.name字段分组统计的实现方法
错误代码原因
你原有代码使用JSON.stringify(obj)作为分组key,会将对象全部属性纳入key的计算逻辑。你提供的示例数据中两本《english book》的version字段值不同,会被判定为两个完全不同的key,因此无法按name字段完成正确统计。
正确实现代码
const oldStockBooks = [ { name: 'english book', author: 'cupello', version: 1, }, { name: 'biology book', author: 'nagazumi', version: 4, }, { name: 'english book', author: 'cupello', version: 2, }, ]; const groupCounter = {}; oldStockBooks.forEach(item => { // 仅用需要分组的name字段作为唯一key const groupKey = item.name; if (!groupCounter[groupKey]) { // 首次匹配到分组时初始化条目,保留指定字段 groupCounter[groupKey] = { name: item.name, author: item.author, total: 0 } } // 统计数累加 groupCounter[groupKey].total += 1; }) // 将统计映射对象转为数组格式,得到预期输出 const output = Object.values(groupCounter);
可选扩展
如果需要同时按name+author两个字段联合分组(避免出现同名书不同作者被合并统计的问题),只需将分组key修改为:
const groupKey = `${item.name}-${item.author}`;
内容的提问来源于stack exchange,提问作者schutte
相关产品推荐
相关产品推荐

