LoginSignup
1
0

More than 5 years have passed since last update.

連想配列の配列からキーごとの配列を抜き出す

Last updated at Posted at 2019-01-27

こういうAPIの返りを

APIの返り値

const apiReturn = [
  {
     id: "3fa85f64-5717-4562-b3fc-2c963f66afa1",
     name: 'taro',
   },
   {
     id: "3fa85f64-5717-4562-b3fc-2c963f66afa2",
     name: 'jiro',
   },
   {
     id: "3fa85f64-5717-4562-b3fc-2c963f66afa3",
     name: 'saburo',
   }
];

こんな風にキーごとに配列にしたかったので

キーごとの配列

[ '3fa85f64-5717-4562-b3fc-2c963f66afa1',
  '3fa85f64-5717-4562-b3fc-2c963f66afa2',
  '3fa85f64-5717-4562-b3fc-2c963f66afa3' ]

[ 'taro', 'jiro', 'saburo' ]

こうした

snippet.js
const apiReturn = [
  {
     id: "3fa85f64-5717-4562-b3fc-2c963f66afa1",
     name: 'taro',
   },
   {
     id: "3fa85f64-5717-4562-b3fc-2c963f66afa2",
     name: 'jiro',
   },
   {
     id: "3fa85f64-5717-4562-b3fc-2c963f66afa3",
     name: 'saburo',
   }
];

const ids = apiReturn.map(x => x.id);
const names = apiReturn.map(x => x.name);

console.log(ids)
console.log(names)

Array.prototype.map() は配列を返すんだな

なんでこんなことがしたかったかというと.... つづく。

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