Map over object preserving keys

后端 未结 12 1429
再見小時候
再見小時候 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 15:03

    A mix fix for the underscore map bug :P

    _.mixin({ 
        mapobj : function( obj, iteratee, context ) {
            if (obj == null) return [];
            iteratee = _.iteratee(iteratee, context);
            var keys = obj.length !== +obj.length && _.keys(obj),
                length = (keys || obj).length,
                results = {},
                currentKey;
            for (var index = 0; index < length; index++) {
              currentKey = keys ? keys[index] : index;
              results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
            }
            if ( _.isObject( obj ) ) {
                return _.object( results ) ;
            } 
            return results;
        }
    }); 
    

    A simple workaround that keeps the right key and return as object It is still used the same way as i guest you could used this function to override the bugy _.map function

    or simply as me used it as a mixin

    _.mapobj ( options , function( val, key, list ) 
    

提交回复
热议问题