map function for objects (instead of arrays)

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

    If you're interested in mapping not only values but also keys, I have written Object.map(valueMapper, keyMapper), that behaves this way:

    var source = { a: 1, b: 2 };
    function sum(x) { return x + x }
    
    source.map(sum);            // returns { a: 2, b: 4 }
    source.map(undefined, sum); // returns { aa: 1, bb: 2 }
    source.map(sum, sum);       // returns { aa: 2, bb: 4 }
    

提交回复
热议问题