magom001
magom001

Reputation: 660

JavaScript Proxies: set does not trigger when modifying objects in an array

I have an array filled with objects

let array_of_objects = [{
  id: 1,
  name: "John"
}, {
  id: 2,
  name: "Bill"
}, {
  id: 3,
  name: "Mike"
}];

I then create a proxy with a set handler and my array as a target

let p = new Proxy(array_of_objects, {
  set: function(target, property, value) {
    //Do something
  })
})

If I call forEach on the proxy:

p.forEach((e) => {
  e.name = "some new value";
});

The set trap of my proxy does not trigger. Whereas manipulating the array (p.push() etc.). Does.

What trap should be used in my case?

Upvotes: 2

Views: 389

Answers (1)

madox2
madox2

Reputation: 51861

You need to create proxy for each object you want to modify. For example you can map your array to wrap each object with proxy:

const p = array_of_objects.map(e => new Proxy(e, {
  set: function(target, property, value, receiver) {
    console.log(target, property, value, receiver)
    // Do something
  }
}));

p.forEach(e => {
    e.name = "some new value";
});

Upvotes: 2

Related Questions