Featured image of post Typescript Dynamic Operation of Object

Typescript Dynamic Operation of Object

TypeScriptでオブジェクトに存在する全てのvalueに何らかの操作をする備忘録。

colors の「赤」を「赤色」に、「緑」を「緑色」に、「青」を「青色」にする。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
type Colors = {
  red: string;
  green: string;
  blue: string;
}

const colors = {
  red: '赤',
  green: '緑',
  blue: '青'
};

const newColors: Colors =
  Object.fromEntries(
    Object.entries(colors).map(([key, value]) => [
      key,
      `${value}色`
    ])
  );

console.log(newColors);
// {
//   "red": "赤色",
//   "green": "緑色",
//   "blue": "青色"
// }

Object.entries(colors) 部分で colors をもとに、文字列をキーとした列挙可能なプロパティの組 [key, value] からなる配列が生成される。

1
2
3
4
5
[
  ['red', '赤'],
  ['green', '緑'],
  ['blue', '青']
]

これにより colors のデータをmapで操作できるようになる。このmapの中でvalueに「色」を追加した、新しい配列を生成する。

1
2
3
4
5
[
  ['red', '赤色'],
  ['green', '緑色'],
  ['blue', '青色']
]

外側の Object.fromEntries により、列挙可能なプロパティの組 [key, value] からなる配列をもとにオブジェクトを生成する。

1
2
3
4
5
{
  'red': '赤色',
  'green': '緑色',
  'blue': '青色'
}

初見だと戸惑うかもしれないが、やっていることはシンプル。


参考