4
4

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 3 years have passed since last update.

[JavaScript] 配列オブジェクトをオブジェクトに変換する4つの実装方法

Last updated at Posted at 2021-04-04

はじめに

配列オブジェクト(オブジェクトを要素に持つ配列)を
オブジェクトに変換する実装方法を4つ紹介します!

問題

// この配列を
const sampleArray = [
  {id: '1', name: 'React'},
  {id: '2', name: 'Angular'},
  {id: '3', name: 'Vue.js'},
];

// こうしたい
{
 '1': { id: '1', name: 'React' },
 '2': { id: '2', name: 'Angular' },
 '3': { id: '3', name: 'Vue.js' },
}

// どうやって実装する?

解法1

for...of...構文を使って実装する

let sampleObj = {}

for(const element of sampleArray) {
    obj1[element.id] = element;
}

console.log(sampleObj);

// 出力結果
{
 '1': { id: '1', name: 'React' },
 '2': { id: '2', name: 'Angular' },
 '3': { id: '3', name: 'Vue.js' },
}

解法2

forEach関数を使って実装する方法

let sampleObj = {}

sampleArray.forEach((cur) =>
  sampleObj[cur.id] = cur;
}

console.log(sampleObj);

// 出力結果
{
 '1': { id: '1', name: 'React' },
 '2': { id: '2', name: 'Angular' },
 '3': { id: '3', name: 'Vue.js' },
}

解法3

reduce関数を用いて実装する

const result = sampleArray.reduce((acc, cur) => {
    acc[cur.id] = cur;
    return acc;
},{})

console.log(result);

// 出力結果
{
 '1': { id: '1', name: 'React' },
 '2': { id: '2', name: 'Angular' },
 '3': { id: '3', name: 'Vue.js' },
}

reduce関数の第二引数に「空オブジェクト」を渡すことで
配列をオブジェクトに変換することができます

解法4

reduce関数とComputed Property Names(MDN)を用いて実装する

const result = sampleArray.reduce((acc, cur) => ({...acc, [cur.id]: cur}), {});

console.log(result);

// 出力結果
{
 '1': { id: '1', name: 'React' },
 '2': { id: '2', name: 'Angular' },
 '3': { id: '3', name: 'Vue.js' },
}

Computed Property Names(MDN)を用いると
処理が1行で書けるのでコードが簡潔になって便利です!

参考文献

for...of... | MDN
forEach | MDN
reduce | MDN

4
4
1

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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?