2
1

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.

TypeScriptで配列からオブジェクトに変換するutil関数を作ってみた

Last updated at Posted at 2019-09-16

[{id: 1, name: "hoge"}, {id: 2, name: "fuga"}]のような配列を{ 1 : {id:1, name: "hoge"}, 2 : { id: 2, name: "fuga" }}のようなidをキーにそれに対応するオブジェクトが値になっているように変換したい時のメモになります。

このutil関数が欲しかった背景としては、reducer内でデータを扱いやすいようにオブジェクトから配列に変換したり、stateに変更を反映させるために配列からオブジェクトに変換することが度々あったからです。

// 配列からオブジェクト(プロパティにidを保持している)に変換する
const fromArrayToObject = <T extends Readonly<{ id: number }>>(
  items: ReadonlyArray<T>
): Readonly<{ [id: number]: T }> =>
  items.reduce<{ [id: number]: T }>((map, item) => {
    map[item.id] = item
    return map
  }, {})

使用例

type Todo = Readonly<{
  id: number
  title: string
  done: boolean
}>

const todoList: ReadonlyArray<Todo> = [
  { id: 1, title: "ラーメン食べる", done: false },
  { id: 2, title: "二郎を食べる", done: false }
]

const result = fromArrayToObject(todoList)

/* 
出力結果
{ 
  '1': { id: 1, title: 'ラーメン食べる', done: false },
  '2': { id: 2, title: '二郎を食べる', done: false } 
}
*/
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?