Search code examples
javascriptarraysobjectprototypehigher-order-functions

How to go about mapping an array object within an object using prototype?


I have some issues with getting prototype map function to work with my array object inside my object. I get the error "x() is not a function". I know that you cant use prototype on objects but arrays within objects should be reachable using obj.arr.map().

Here is my code:

let data = [

{'a':1, 'b':2, 'c':3},
{'a':4, 'b':5, 'c':6},
{'a':7, 'b':8, 'c':9}

]

let mapped = data.map(function(data){

  let newMap = {}
  newMap['a']=data['a']
  newMap['b']=data['b']
  return newMap;

});

Mapping.prototype.protoMap = function(){

//I have tried writing it as map.data

  let protoMap = map.map(function(map){

    let protoMap1 = {}

    protoMap1['a'] = map.mappedData['a']

    return protoMap1;

  });

}

function Mapping(data = []){

  this.mappedData = data

};

let map = new Mapping(mapped);


Solution

  • Try to stay away from using global variables:

    Mapping.prototype.protoMap = function() {
      // DON'T do this
      // plus, this really doesn't make sense
      // because `map` refers to the new `Mapping` object that
      // you created; what you probably want to do is use the `mappedData`
      // property on your newly created `Mapping` object
      // const protoMap = map.mappedData.map(function(map) {...})
    
      // instead, use `this` to access the `mappedData` property
      // that you passed to the constructor
      const protoMap = this.mappedData.map(function(item) {...})
    }
    const map = new Mapping(mapped)
    

    See comments in the code snippet to figure out how to fix your example.

    function Mapping(data = []) {
      this.mappedData = data
    }
    Mapping.prototype.protoMap = function() {
      // access the `mappedData` that was passed
      // to the `Mapping` constructor using `this`
      const protoMap = this.mappedData.map(
        function(item) {
          // use `item` argument for the `mappedData.map`
          // callback to access each item inside `mappedData`
          // individually
          const temp = {}
          temp["a"] = item["a"]
          return temp
        }
      )
      return protoMap
    }
    
    const data = [
      {'a': 1, 'b': 2, 'c': 3},
      {'a': 4, 'b': 5, 'c': 6},
      {'a': 7, 'b': 8, 'c': 9}
    ]
    
    const mapped = data.map(
      function(data) {
        const newMap = {}
        newMap['a']=data['a']
        newMap['b']=data['b']
        return newMap;
      }
    )
    
    const mapping = new Mapping(mapped)
    const result = mapping.protoMap()
    
    console.log('result', result)