LoginSignup
3
1

More than 3 years have passed since last update.

配列の中にあるオブジェクトの値をキーにして新しいオブジェクトを作る

Last updated at Posted at 2019-07-12

あるAPIを叩いてデータを取得した時に、このような構造の配列が返ってくる事って多いと思います。

[
  {id: 1, name: 'hoge'},
  {id: 2, name: 'fuga'},
  {id: 3, name: 'piyo'}
]

この構造のままデータを扱うのは結構大変なので、下のようなオブジェクトのidの値をキーにした新しいオブジェクトを作りたい事ってよくありませんか?

{
  1: {id: 1, name: 'hoge'},
  2: {id: 2, name: 'fuga'},
  3: {id: 3, name: 'piyo'}
}

という訳で、配列の中にあるオブジェクトの値をキーにして新しいオブジェクトを作る

ES2018 / オブジェクトのスプレッド構文を使う

const array = [
  {id: 1, name: 'hoge'},
  {id: 2, name: 'fuga'},
  {id: 3, name: 'piyo'}
];

const result = array.reduce((accumulator, currentValue) => {
  return {...accumulator, [currentValue.id]: currentValue}
},{})

console.log(result) 

// 結果↓
//
// {
//   1: {id: 1, name: "hoge"}
//   2: {id: 2, name: "fuga"}
//   3: {id: 3, name: "piyo"}
// }

lodash / _.mapKeys() を使う

const array = [
  {id: 1, name: 'hoge'},
  {id: 2, name: 'fuga'},
  {id: 3, name: 'piyo'}
];

const result = _.mapKeys(array, (data) => data.id)

console.log(result)

// 結果↓
//
// {
//   1: {id: 1, name: "hoge"}
//   2: {id: 2, name: "fuga"}
//   3: {id: 3, name: "piyo"}
// }

まとめ

個人的には、lodash の_.mapKeys()を使う方がコードがスッキリして好きです。

3
1
2

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
3
1