嗨,我正在尝试使用减少方法从对象数组中创建一个对象映射,但是没有找到添加2个属性作为键的方法。假设我有一系列的物体,比如-
 const students = [
    {
      name: "sam",
      age: 26,
    },
    {
      name: 'john",
      age: 30,
    }
    ]我正试着创建一张地图
{
  sam_26:{
      name: "sam",
      age: 26,
    }
 }我的精简函数代码:
students.reduce((obj, student) => {
    `${obj[student.name]}_${obj[student.age]}` = student;
    return obj;
  }, {});这不管用。任何指针都会对..thanks有帮助!
发布于 2018-04-23 04:32:54
使用从student对象获取的值创建键。使用student将当前的key分配给obj (累加器)
const students = [{
    name: "sam",
    age: 26,
  },
  {
    name: "john",
    age: 30,
  }
];
const result = students.reduce((obj, student) => {
  const key = `${student.name}_${student.age}`;
  obj[key] = student;
  return obj;
}, {});
console.log(result);
使用回调创建键的通用方法:
const keyBy = (arr, cb) => 
  arr.reduce((r, o) => {
    const key = cb(o);
    r[key] = o;
    return r;
  }, {});
  
const students = [{"name":"sam","age":26},{"name":"john","age":30}];  
const result = keyBy(students, (o) => `${o.name}_${o.age}`);
console.log(result);
发布于 2018-04-23 04:33:49
您不能用这样的模板文字将其分配到左侧。尝试先定义属性,然后将其分配给对象:
const students = [ { name: "sam", age: 26, }, { name: 'john', age: 30, } ];
const finalObj = students.reduce((obj, student) => {
  const prop = `${student.name}_${student.age}`;
  obj[prop] = student;
  return obj;
}, {});
console.log(finalObj);
发布于 2018-04-23 04:39:19
我试过这个剧本,它成功了。只需根据学生姓名和年龄创建变量名,然后将其重新分配给对象。
students.reduce((obj, student) => {
    var name = student.name + '-' + student.age;
    obj[name] = student;
    return obj;
  }, {});https://stackoverflow.com/questions/49973435
复制相似问题