map function for objects (instead of arrays)

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

    Define a function mapEntries.

    mapEntries takes a callback function that is called on each entry in the object with the parameters value, key and object. It should return the a new value.

    mapEntries should return a new object with the new values returned from the callback.

    Object.defineProperty(Object.prototype, 'mapEntries', {
      enumerable: false,
      value: function (mapEntriesCallback) {
        return Object.fromEntries(
          Object.entries(this).map(
            ([key, value]) => [key, mapEntriesCallback(value, key, this)]
          )
        )
      }
    })
    
    
    // Usage example:
    
    var object = {a: 1, b: 2, c: 3}
    var newObject = object.mapEntries(value => value * value)
    console.log(newObject)
    //> {a: 1, b: 4, c: 9}
    

    Edit: A previous version didn't specify that this is not an enumerable property

提交回复
热议问题