You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用reduce方法将对象数组转为双属性键对象映射遇阻

解决用reduce将对象数组转为双属性拼接键的对象映射问题

我来帮你搞定这个问题!你当前的代码出问题的核心是赋值语句的左操作数写法错误,还错误引用了累加器对象里不存在的属性。咱们一步步修正:

问题分析

你的原代码里:

students.reduce((obj, student) => { `${obj[student.name]}_${obj[student.age]}` = student; return obj; }, {});

有两个关键错误:

  1. 你试图用${obj[student.name]}_${obj[student.age]}作为赋值目标,但初始obj是空对象,obj[student.name]和obj[student.age]都是undefined,拼接后是undefined_undefined,而且这种表达式根本不能作为赋值的左操作数。
  2. 你应该直接取当前遍历到的student对象的name和age属性拼接键,而不是去空的累加器里找(累加器刚开始没有任何属性)。

正确实现代码

const students = [ { name: "sam", age: 26 }, { name: "john", age: 30 } ];

// 正确的reduce写法
const studentMap = students.reduce((acc, currentStudent) => {
  // 用当前学生的name和age拼接成唯一键
  const key = `${currentStudent.name}_${currentStudent.age}`;
  // 给累加器添加键值对
  acc[key] = currentStudent;
  // 返回更新后的累加器
  return acc;
}, {});

console.log(studentMap);
// 输出结果:
// { 
//   sam_26: { name: 'sam', age: 26 }, 
//   john_30: { name: 'john', age: 30 } 
// }

额外提示

如果你的数组中存在重复的name_age组合,后面的对象会覆盖前面的(这是对象键的唯一性决定的)。如果需要保留所有重复项,可以把值设为数组:

const studentMapWithDuplicates = students.reduce((acc, currentStudent) => {
  const key = `${currentStudent.name}_${currentStudent.age}`;
  // 如果键已存在,就把当前对象push进数组,否则初始化数组
  acc[key] = acc[key] ? [...acc[key], currentStudent] : [currentStudent];
  return acc;
}, {});

内容的提问来源于stack exchange,提问作者user429035

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:55:30