Posted at

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

More than 1 year has passed since last update.

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"
// }
// }