LoginSignup
2
1

More than 5 years have passed since last update.

ES6 オブジェクトの配列を特定のキーでオブジェクトに変換

Posted at

Array.prototype.reduce()を使う.
accに前回の結果が入ってバケツリレーされていくので、同一キーがあった場合後に実行される方が残る.

let arr = [
  { name: "Newton", age: 84, role: "Physicist" },
  { name: "Newton", age: 84, role: "Mathematician" },
  { name: "Newton", age: 84, role: "Economist" },
  { name: "Mozart", age: 35, role: "Musician" },
  { name: "Darwin", age: 73, role: "Biologist" },
  { name: "Newton", age: 84, role: "Alchemist" },
  { name: "Mozart", age: 35, role: "Composer" },
]

let objects = arr.reduce((acc,value)=>{
  acc[value.name] = value
  return acc
}, {})

console.log(objects)
// {
//   "Newton": {
//     "name": "Newton",
//     "age": 84,
//     "role": "Alchemist"
//   },
//   "Mozart": {
//     "name": "Mozart",
//     "age": 35,
//     "role": "Composer"
//   },
//   "Darwin": {
//     "name": "Darwin",
//     "age": 73,
//     "role": "Biologist"
//   }
// }
2
1
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
2
1