使用reduce方法将对象数组转为双属性键对象映射遇阻
解决用reduce将对象数组转为双属性拼接键的对象映射问题
我来帮你搞定这个问题!你当前的代码出问题的核心是赋值语句的左操作数写法错误,还错误引用了累加器对象里不存在的属性。咱们一步步修正:
问题分析
你的原代码里:
students.reduce((obj, student) => { `${obj[student.name]}_${obj[student.age]}` = student; return obj; }, {});
有两个关键错误:
- 你试图用
${obj[student.name]}_${obj[student.age]}作为赋值目标,但初始obj是空对象,obj[student.name]和obj[student.age]都是undefined,拼接后是undefined_undefined,而且这种表达式根本不能作为赋值的左操作数。 - 你应该直接取当前遍历到的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
相关产品推荐
相关产品推荐

