-2

Let's say I have an array 'x' and array x has 100 instances of an object. Lets say after I made this array of instances, I wanted to add an additional method to each instance within array x, how would I go about doing this?

Thanks!

Josh Owens
  • 87
  • 1
  • 1
  • 3
  • 1
    Why not add the method to the object before filling the array? – Ryan Wilson Jul 13 '22 at 21:16
  • 2
    Anything wrong with iterating the array and adding the method to the objects? – trincot Jul 13 '22 at 21:16
  • Use a loop to reduce the problem to “add an additional method to a single object”. Methods are just properties in JavaScript, so it’s “set a property on an object”. – Ry- Jul 13 '22 at 21:17
  • duplicate: [Add property to an array of objects](https://stackoverflow.com/questions/38922998/add-property-to-an-array-of-objects) – pilchard Jul 13 '22 at 21:20

2 Answers2

2

If they are instances of some common class try this:

// create a class
class Item {
  constructor() {
    this.x = Math.random() * 10 | 0;
  }
}

// create instances
const items = [...Array(100).keys()].map(() => new Item())

// add missing method
Item.prototype.print = function() {
  console.log(this.x)
}

// test added method
items.forEach(item => item.print())

In the other case, you can just add a function to each instance

// generate objects
const items = [...Array(100).keys()].map(() => ({
  x: Math.random() * 10 | 0
}))

// add a function to each object
items.forEach(item => item.print = function() {
  console.log(this.x)
})

// test the added function
items.forEach(item => item.print())
Konrad
  • 21,590
  • 4
  • 28
  • 64
0

Use a for loop to iterate over the array items and assign your method to each object:

x = [...];
for (var i = 0; i < x.length ; i++) {
    x[i].method = func () {...};
}
IT goldman
  • 14,885
  • 2
  • 14
  • 28
TheEagle
  • 5,808
  • 3
  • 11
  • 39