guneysus
guneysus

Reputation: 6502

Java Script mapping objects method to a object in an array?

I know how to apply a method whole array with myArray.map( fn ).

Although it looks weird and awkward, I want to run each objects method taking parameter as it self. Like

function MyObject(i) {
 this.i = i;
 this.internalMethod = function () {
     return this.i * 100
   }
}

function externalMethod(object){
   return object.i * 100
}

var objects = [new MyObject(3), new MyObject(-1), new MyObject(5)]
objects.map ( externalMethod ) // This works but
/// [300, -100, 500]

objects.map ( arrayElements.internalMethod )

Upvotes: 0

Views: 28

Answers (1)

bloodyKnuckles
bloodyKnuckles

Reputation: 12089

Wrap the internal function in an anonymous function and pass it the currently mapped object.

JSFiddle

var newObj = objects.map(function(curr) {
    return curr.internalMethod()
});
console.log(newObj)
// [300, -100, 500]

Upvotes: 1

Related Questions