map function for objects (instead of arrays)

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

    Based on @Amberlamps answer, here's a utility function (as a comment it looked ugly)

    function mapObject(obj, mapFunc){
        return Object.keys(obj).reduce(function(newObj, value) {
            newObj[value] = mapFunc(obj[value]);
            return newObj;
        }, {});
    }
    

    and the use is:

    var obj = {a:1, b:3, c:5}
    function double(x){return x * 2}
    
    var newObj = mapObject(obj, double);
    //=>  {a: 2, b: 6, c: 10}
    

提交回复
热议问题