ikemonn's blog

技術ネタをちょこちょこと

【Underscore.js】_.mapObjectを読んだ

jashkenas/underscore_.mapObjectを読んだ。

概要

_.mapObject(object, iteratee, [context])

objectの各値に第2引数で指定した関数を適用した第1引数を返す。.mapは値の配列を返すが、.mapObjectはオブジェクトを返す。

_.mapObject({age: 20, score: 50}, function(val, key){
    return val + 5;
}); // {age: 25, score: 55}

_.map({age: 20, score: 50}, function(val, key){
    return val + 5;
}); // [25, 55]

ソースコード

_.mapObject = function(obj, iteratee, context) {
    iteratee = cb(iteratee, context);
    var keys =  _.keys(obj),
          length = keys.length,
          results = {},
          currentKey;
      for (var index = 0; index < length; index++) {
        currentKey = keys[index];
        results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
      }
      return results;
  };

_.mapとは違い、返す値をpushしていくresutlsがオブジェクトになっており、そのkeyには元のオブジェクトのkeyを指定している。

参考

jashkenas/underscore