map function for objects (instead of arrays)

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

    This is really annoying, and everyone in the JS community knows it. There should be this functionality:

    const obj1 = {a:4, b:7};
    const obj2 = Object.map(obj1, (k,v) => v + 5);
    
    console.log(obj1); // {a:4, b:7}
    console.log(obj2); // {a:9, b:12}
    

    here is the naïve implementation:

    Object.map = function(obj, fn, ctx){
    
        const ret = {};
    
        for(let k of Object.keys(obj)){
            ret[k] = fn.call(ctx || null, k, obj[k]);
        });
    
        return ret;
    };
    

    it is super annoying to have to implement this yourself all the time ;)

    If you want something a little more sophisticated, that doesn't interfere with the Object class, try this:

    let map = function (obj, fn, ctx) {
      return Object.keys(obj).reduce((a, b) => {
        a[b] = fn.call(ctx || null, b, obj[b]);
        return a;
      }, {});
    };
    
    
    const x = map({a: 2, b: 4}, (k,v) => {
        return v*2;
    });
    

    but it is safe to add this map function to Object, just don't add to Object.prototype.

    Object.map = ... // fairly safe
    Object.prototype.map ... // not ok
    

提交回复
热议问题