0
1

More than 1 year has passed since last update.

配列を連想配列に変換する (JavaScript)

Last updated at Posted at 2022-07-18

概要

キーとなるプロパティを持つオブジェクトの配列を連想配列に変換する場合、Array.prototype.reduce()Object.defineProperty()を使って以下のように書ける。

index.js
const hash = array.reduce((p, c) => Object.defineProperty(p, c.key, { value: c }), {}); 

補遺:コメントで頂いた方法がコンパクトなのでそちらも参照

サンプルコード

配列を連想配列に変換し、キーを使って値を取り出すサンプルコード。

sample.js
const array = [
  { code: 'F001', name: 'Apple', price: 250 },
  { code: 'F002', name: 'Banana', price: 200 },
  { code: 'F003', name: 'Cherry', price: 500 },
  { code: 'F004', name: 'Durian', price: 5000 },
];

const hash = array.reduce((p, c) => Object.defineProperty(p, c.code, { value: c }), {}); 

console.log(hash['F003'].name); // Cherry
0
1
4

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
1