Map over object preserving keys

后端 未结 12 1420
再見小時候
再見小時候 2020-12-07 14:41

The map function in underscore.js, if called with a javascript object, returns an array of values mapped from the object\'s values.

_.map({one:          


        
12条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 14:56

    I know this is old, but now Underscore has a new map for objects :

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

    You can of course build a flexible map for both arrays and objects

    _.fmap = function(arrayOrObject, fn, context){
        if(this.isArray(arrayOrObject))
          return _.map(arrayOrObject, fn, context);
        else
          return _.mapObject(arrayOrObject, fn, context);
    }
    

提交回复
热议问题