map function for objects (instead of arrays)

前端 未结 30 1957
无人及你
无人及你 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:54

    var myObject = { 'a': 1, 'b': 2, 'c': 3 };
    
    
    Object.prototype.map = function(fn){
        var oReturn = {};
        for (sCurObjectPropertyName in this) {
            oReturn[sCurObjectPropertyName] = fn(this[sCurObjectPropertyName], sCurObjectPropertyName);
        }
        return oReturn;
    }
    Object.defineProperty(Object.prototype,'map',{enumerable:false});
    
    
    
    
    
    newObject = myObject.map(function (value, label) {
        return value * value;
    });
    
    
    // newObject is now { 'a': 1, 'b': 4, 'c': 9 }
    

提交回复
热议问题