LoginSignup
0
0

More than 1 year has passed since last update.

【TypeScript】配列の中に同じキーの連想配列をまとめる

Posted at

はじめに

TypeScriptでタイトルに記載してあることをしたので記事にすることにしました。
さっそく結論に入ります!
※タイトル分かり辛いかもです。悩んだ末にこれにしました😅
 もっと良いタイトルを思いついたらタイトル名変わるかもです…

結論

const initDataArray: {[key: string]: string|number}[] = [
  {"id": 1, "name": "リンゴ", "type": "果物"},
  {"id": 2, "name": "ブドウ", "type": "果物"},
  {"id": 3, "name": "ミカン", "type": "果物"},
  {"id": 4, "name": "人参", "type": "野菜"},
  {"id": 5, "name": "キャベツ", "type": "野菜"},
  {"id": 6, "name": "ピーマン", "type": "野菜"},
];
const sortArray: any = new Array();

for(let initData of initDataArray) {
  if(!initData["type"]) continue;
  // 空の配列追加。push時に下記エラーが発生するため。
  // TypeError: Cannot read properties of undefined (reading 'push')
  if(!sortArray[initData["type"]]) sortArray[initData["type"]] = new Array();
  sortArray[initData["type"]].push(initData);
}

console.log(sortArray);

配列の中に同じキーの連想配列をまとめることができました!
配列の中身.png

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