20
21

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】連想配列(Object)でmap関数の処理をしたい

Last updated at Posted at 2020-05-12

やりたいこと

JavaScriptのmap関数は、配列の値に対し処理を適用することで新しい配列を返す便利な関数です。これを連想配列(Object)に対しても使いたい場合、どのように書けば良いのかサンプルを紹介します。なお、map関数については【JavaScript】map関数を用いたおしゃれな配列処理を参照ください。

前提や参考記事など

サンプルコード

sample.js
const beforeObject = {
  test1: 1,
  test2: 2
};

// 2倍にする
const afterObject = Object.keys(beforeObject).reduce(
  (after, key) => ({
    ...after,
    [key]: beforeObject[key] * 2
  }),
  {}
);

結果

{ test1: 1, test2: 2 }{ test1: 2, test2: 4 }に変換されます。

追記(2020/5/13)

@ttatsf さんにコメント頂きましたが、ES2019から追加されたObject.fromEntriesで以下のようにも書けます。
Object.fromEntries()でオブジェクトをmapするの記事も参考になります。

sample.js
const afterObject = Object.fromEntries(
  Object.entries( beforeObject )
  .map( ( [ _, value ] ) => [ _, value * 2 ] )
)
20
21
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
20
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?