map function for objects (instead of arrays)

前端 未结 30 2421
无人及你
无人及你 2020-11-22 04:23

I have an object:

myObject = { \'a\': 1, \'b\': 2, \'c\': 3 }

I am looking for a native method, similar to Array.prototype.map

30条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 04:58

    The map function does not exist on the Object.prototype however you can emulate it like so

    var myMap = function ( obj, callback ) {
    
        var result = {};
    
        for ( var key in obj ) {
            if ( Object.prototype.hasOwnProperty.call( obj, key ) ) {
                if ( typeof callback === 'function' ) {
                    result[ key ] = callback.call( obj, obj[ key ], key, obj );
                }
            }
        }
    
        return result;
    
    };
    
    var myObject = { 'a': 1, 'b': 2, 'c': 3 };
    
    var newObject = myMap( myObject, function ( value, key ) {
        return value * value;
    });
    

提交回复
热议问题