从键创建js对象属性

时间:2018-04-23 04:29:56

标签: javascript arrays reduce

嗨我正在尝试使用reduce方法从对象数组创建对象映射,但没有找到将2个属性添加为键的方法。假设我有像 -

这样的对象数组
 const students = [
    {
      name: "sam",
      age: 26,
    },
    {
      name: 'john",
      age: 30,
    }
    ]

我正在尝试制作像

这样的地图
{
  sam_26:{
      name: "sam",
      age: 26,
    }
 }

我的reduce函数代码:

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

这没用。任何指针都会有所帮助..谢谢!

4 个答案:

答案 0 :(得分:5)

使用从student对象获取的值创建密钥。使用student将当前obj分配给key(累加器):

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);

答案 1 :(得分:1)

您无法使用类似的模板文字指定左侧。首先尝试定义属性,然后将其分配给对象:

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);

答案 2 :(得分:1)

我尝试过这个脚本,但它确实有效。只需根据学生姓名和年龄创建变量名称,然后分配回对象

students.reduce((obj, student) => {
    var name = student.name + '-' + student.age;
    obj[name] = student;
    return obj;
  }, {});

答案 3 :(得分:1)

希望这段代码很有用

const students = [{
    name: "sam",
    age: 26,
  },
  {
    name: "john",
    age: 30,
  }
]
//Using reduce function to add value to the accumalator
var x = students.reduce(function(acc, curr, index) {
  // Here acc is the object which is passed as argument,
  //In this object checking if it has a key like sam_26 & so on
  if (!acc.hasOwnProperty([curr['name'] + '_' + curr['age']])) {
    //if not then add the key and add relevant vakues to it
    acc[curr.name + '_' + curr.age] = {
      name: curr.name,
      age: curr.age
    }
  }
  return acc;
}, {});
console.log(x)