LoginSignup
1
2

More than 3 years have passed since last update.

array.mapでオブジェクトの配列から新しいオブジェクトの配列を返す

Last updated at Posted at 2020-03-03

業務で必要になって調べたので備忘録です。

const petList = [
  {
    name: 'hana',
    kind: 'dog',
    old: 8,
  },
  {
    name: 'maruo',
    kind: 'cat',
    old: 5,
  },
  {
    name: 'sora',
    kind: 'dog',
    old: 6,
  }
]

array.mapでオブジェクトの配列から1つのプロパティだけ抜き出す

オブジェクトの配列から特定のプロパティだけ抜き出した配列を作る場合には、
お馴染みの書き方でいけます。


const petNames = petList.map(pet => pet.name)
console.log(petNames)
//["hana", "maruo", "sora"]

array.mapでオブジェクトの配列から新しいオブジェクトの配列を返す

各値から以下のようなオブジェクトを作って、その配列を返したい場合があるとします。


{
  name: 'hana@8歳',
  kind: 'dog'
}

以下のように書きます。
{ name: pet.name@pet.old歳, kind: pet.kind}でオブジェクトを作ってあげて、それを()で囲みます。

const newPetList = petList.map(pet => ({ name: `${pet.name}@${pet.old}歳`, kind: pet.kind }))
console.log(newPetList)
//[{ name: "hana@8歳", kind: "dog"}, { name: "maruo@5歳", kind: "cat"}, { name: "sora@6歳", kind: "dog"}]

まとめ

array.mapは最高

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