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?
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";
});