1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ES6の分割代入

Posted at

問題

二次元配列をオブジェクトの配列に変換する。

問題
const classes = [
  [ '化学', '1時限目', '鈴木先生' ],
  [ '物理', '2時限目', '佐藤先生'],
  [ '数学', '3時限目', '木村先生' ]
];

//これをこうしたい。
const classesAsObject = [
    { subject:'化学', time: '1時限目', teacher: '鈴木先生'},
    { subject:'物理', time: '2時限目', teacher: '佐藤先生'},
    { subject:'数学', time: '3時限目', teacher: '木村先生'}
]

#ES5で書く
器となる配列を先に宣言しておいて、forループの中で作成したオブジェクトをその配列に放り込んでいく。

var classesAsObject = [];
for (var i=0; i<classes.length; i++) {
  var element = { 
    subject: classes[i][0],
    time: classes[i][1],
    teacher: classes[i][2]
  }
  classesAsObject.push(element);
};

ES6で書く

引数を分割代入で受け取ってオブジェクトリテラルを返すmapを作る。

const classesAsObject = classes.map(([subject, time, teacher])=> {
    return {subject, time, teacher};
});

何を使っているか

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?