map function for objects (instead of arrays)

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

    You could use Object.keys and then forEach over the returned array of keys:

    var myObject = { 'a': 1, 'b': 2, 'c': 3 },
        newObject = {};
    Object.keys(myObject).forEach(function (key) {
        var value = myObject[key];
        newObject[key] = value * value;
    });
    

    Or in a more modular fashion:

    function map(obj, callback) {
        var result = {};
        Object.keys(obj).forEach(function (key) {
            result[key] = callback.call(obj, obj[key], key, obj);
        });
        return result;
    }
    
    newObject = map(myObject, function(x) { return x * x; });
    

    Note that Object.keys returns an array containing only the object's own enumerable properties, thus it behaves like a for..in loop with a hasOwnProperty check.

提交回复
热议问题