Array.prototype.reduceの使い方

(前回の内容も踏まえて)そうか、こういう使い方もできるのか。

 

今回はJavascriptだけど。

今まで上のようなやりかたで書いていて、 最初に空のオブジェクトを宣言するのが嫌だったんだけど、reduce使えばよかったのか。

var hash = {};
["a", "b", "c", "d"].forEach((v)=>{
  hash[v] = v.toUpperCase();
});
 
console.dir(hash);
// => { a: 'A', b: 'B', c: 'C', d: 'D' }
 
var hash = ["a", "b", "c", "d"].reduce((obj, v)=>{
  obj[v] = v.toUpperCase();
  return obj;
}, {})
 
console.dir(hash);
// => { a: 'A', b: 'B', c: 'C', d: 'D' }