将数组映射到对象中,未定义键

时间:2016-12-29 11:05:32

标签: arrays dictionary ecmascript-6

const lessons = [
  [ 'Chemistry', '9AM', 'Mr. Darnick' ],
  [ 'Physics', '10:15AM', 'Mrs. Lithun'],
  [ 'Math', '11:30AM', 'Mrs. Vitalis' ]
];

let lessonsAsObject = {};

lessons.map(lesson => {
    lessonsAsObject[lesson[subject]] = lesson[0];
});

我想将此数组转换为对象,将数据与键,主题,时间和教师相匹配。

但是上面的代码返回

  

引用错误,“主题未定义”。

2 个答案:

答案 0 :(得分:0)

如果你想要最终得到的是一个对象数组,其中对象已命名属性而不是数组位置,那么你可以这样做:

var lessonsList = lessons.map(function(lesson) {
    return {subject: lesson[0], time: lesson[1], teacher: lesson[2]};
});

这会给你一个像这样的对象数组:

[{subject: "Chemistry", time: "9AM", teacher: "Mr. Darnick"}, 
 {subject: "Physics", time: "10:15AM", teacher: "Mrs. Lithun"}, 
 {subject: "Math", time: "11:30AM", teacher: "Mrs. Vitalis"}]

如果您正在寻找某种不同类型的输出,请详细说明您尝试实现的输出。

  

但是上面的代码返回引用错误," subject不是   定义"

这是因为标识符subject未在任何地方定义。如果您打算将其用作静态属性名称,则可以执行lesson["subject"]。如果您打算让subject成为包含某个属性名称的变量,那么您必须定义并分配该变量。

答案 1 :(得分:0)

您可以使用array destructuring从数组中获取参数,然后使用shorthand and computed property names为每个参数创建一个对象。

如果您希望最终结果是对象而不是对象数组,则可以使用spread syntaxObject#assign将它们组合到一个对象:

您可以将主题用作键:



const lessons = [["Chemistry","9AM","Mr. Darnick"],["Physics","10:15AM","Mrs. Lithun"],["Math","11:30AM","Mrs. Vitalis"]];

const lessonsAsObject = Object.assign(...lessons.map(([subject, time, teacher])=> ({ 
  [subject]: { 
    time,
    teacher 
  }
})));

console.log(lessonsAsObject);




或索引为关键:



const lessons = [["Chemistry","9AM","Mr. Darnick"],["Physics","10:15AM","Mrs. Lithun"],["Math","11:30AM","Mrs. Vitalis"]];

const lessonsAsObject = Object.assign(...lessons.map(([subject, time, teacher], index)=> ({ 
  [index]: {
    subject,
    time,
    teacher 
  }
})));

console.log(lessonsAsObject);




如果你只想要一个对象数组:



const lessons = [["Chemistry","9AM","Mr. Darnick"],["Physics","10:15AM","Mrs. Lithun"],["Math","11:30AM","Mrs. Vitalis"]];

const lessonsAsObject = lessons.map(([subject, time, teacher])=> ({ subject, time, teacher }));

console.log(lessonsAsObject);