1
0

More than 3 years have passed since last update.

Object.keys(obj).reduceで新しいオブジェクトを作る

Last updated at Posted at 2021-03-10

あるオブジェクトがある。

const fruits = {
 apple: '赤',
 orange: '橙',
 lemon: '黄'
}

このオブジェクトのキーを利用して新しいオブジェクトを作りたい時にObject.keys(obj).reduceを使用する。

const fruit2 = Object.keys(fruits).reduce((acc, key) => ({
 ...acc,
 [key]: '果物'
}), {})

// { apple: '果物', orange: '果物', lemon: '果物' }

reduce関数は第1引数に配列一つ一つに対して実行したい処理を、第2引数に初期値を設定する。

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