map function for objects (instead of arrays)

前端 未结 30 2708
无人及你
无人及你 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 05:01

    It's pretty easy to write one:

    Object.map = function(o, f, ctx) {
        ctx = ctx || this;
        var result = {};
        Object.keys(o).forEach(function(k) {
            result[k] = f.call(ctx, o[k], k, o); 
        });
        return result;
    }
    

    with example code:

    > o = { a: 1, b: 2, c: 3 };
    > r = Object.map(o, function(v, k, o) {
         return v * v;
      });
    > r
    { a : 1, b: 4, c: 9 }
    

    NB: this version also allows you to (optionally) set the this context for the callback, just like the Array method.

    EDIT - changed to remove use of Object.prototype, to ensure that it doesn't clash with any existing property named map on the object.

提交回复
热议问题