map function for objects (instead of arrays)

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

    I needed a version that allowed modifying the keys as well (based on @Amberlamps and @yonatanmn answers);

    var facts = [ // can be an object or array - see jsfiddle below
        {uuid:"asdfasdf",color:"red"},
        {uuid:"sdfgsdfg",color:"green"},
        {uuid:"dfghdfgh",color:"blue"}
    ];
    
    var factObject = mapObject({}, facts, function(key, item) {
        return [item.uuid, {test:item.color, oldKey:key}];
    });
    
    function mapObject(empty, obj, mapFunc){
        return Object.keys(obj).reduce(function(newObj, key) {
            var kvPair = mapFunc(key, obj[key]);
            newObj[kvPair[0]] = kvPair[1];
            return newObj;
        }, empty);
    }
    

    factObject=

    {
    "asdfasdf": {"color":"red","oldKey":"0"},
    "sdfgsdfg": {"color":"green","oldKey":"1"},
    "dfghdfgh": {"color":"blue","oldKey":"2"}
    }
    

    Edit: slight change to pass in the starting object {}. Allows it to be [] (if the keys are integers)

提交回复
热议问题