map function for objects (instead of arrays)

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

    To responds more closely to what precisely the OP asked for, the OP wants an object:

    myObject = { 'a': 1, 'b': 2, 'c': 3 }

    to have a map method myObject.map,

    similar to Array.prototype.map that would be used as follows:

    newObject = myObject.map(function (value, label) {
        return value * value;
    });
    // newObject is now { 'a': 1, 'b': 4, 'c': 9 }

    The imho best (measured in terms to "close to what is asked" + "no ES{5,6,7} required needlessly") answer would be:

    myObject.map = function mapForObject(callback)
    {
      var result = {};
      for(var property in this){
        if(this.hasOwnProperty(property) && property != "map"){
          result[property] = callback(this[property],property,this);
        }
      }
      return result;
    }
    

    The code above avoids intentionally using any language features, only available in recent ECMAScript editions. With the code above the problem can be solved lke this:

    myObject = { 'a': 1, 'b': 2, 'c': 3 };
    
    myObject.map = function mapForObject(callback)
    {
      var result = {};
      for(var property in this){
        if(this.hasOwnProperty(property) && property != "map"){
          result[property] = callback(this[property],property,this);
        }
      }
      return result;
    }
    
    newObject = myObject.map(function (value, label) {
      return value * value;
    });
    console.log("newObject is now",newObject);
    alternative test code here

    Besides frowned upon by some, it would be a possibility to insert the solution in the prototype chain like this.

    Object.prototype.map = function(callback)
    {
      var result = {};
      for(var property in this){
        if(this.hasOwnProperty(property)){
          result[property] = callback(this[property],property,this);
        }
      }
      return result;
    }
    

    Something, which when done with careful oversight should not have any ill effects and not impact map method of other objects (i.e. Array's map).

提交回复
热议问题