JavaScript Proxies: no activation of 'set' when making changes to objects within an array

I am working with an array that is filled with objects

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

Next, I create a proxy with a set handler using my array as the target

let proxy = new Proxy(objectArray, {
  set: function(target, property, value) {
    //Handle the set action
  })
})

When I try to use forEach on the proxy:

proxy.forEach((element) => {
  element.name = "updated value";
});

The set trap in my proxy does not trigger, even though array manipulation methods like p.push() do.

Which trap should I use in this scenario?

Answer №1

To modify objects, it is necessary to create a proxy for each object. For instance, you can use array mapping to wrap each object with a proxy:

const modifiedObjects = array.map(obj => new Proxy(obj, {
  set: function(target, prop, val, receiver) {
    console.log(target, prop, val, receiver);
    // Perform actions here
  }
}));

modifiedObjects.forEach(obj => {
    obj.property = "new value";
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using async method in controller with NestJS Interceptor

I am seeking a way to capture both the result and any potential errors from an asynchronous method within a controller using an interceptor. When an error is thrown, the interceptor can respond accordingly. However, I am struggling to figure out how to tri ...

Streaming the request body in NodeJS using ExpressJS without buffering

Looking for a solution to process requests with no specified content-type as binary files. const app = express(); app.use(bodyParser.raw({type: (req) => !req.headers['content-type'], limit: '500mb' })); Some of these files can be ...

Constructing a Primeng MessageService causes a blank webpage to appear

After downloading the QuickStart CLI of PrimeNG for Angular, I added a second component for a chart that was already included in the UI components. Everything seemed to be set up correctly, but when I saved, I ended up with a completely blank page for the ...

AngularJS making a HttpPost request resulting in a 500-Internal Server Error

I'm currently working on an application where I need to include a user in the database which requires a POST operation. However, every time I try to run the application, I encounter a 500-Internal Server Error for the POST API call. Here is a snippe ...

Displaying selected checkbox values in a URL with parameters using PHP and JavaScript

I am looking to extract the selected checkbox value and append it to the browser URL with a parameter name. Below is my HTML code: <div style="width:200px; float:left"> Price <div> <input type="checkbox" name="price" value="0-1 ...

Bring in a collection of classes of various types from one TypeScript file to another

In my code file exampleA.ts, I define an object as follows: import { ExampleClass } from 'example.ts'; export const dynamicImportations = { ExampleClass }; Later, in another file named exampleB.ts, I import an array that includes class types and ...

Implementing a hamburger menu across various webpages

I recently followed a tutorial on adding a hamburger menu from this YouTube video. The menu works perfectly on the INDEX.html page, but when I try to add the same code to other pages like "contact" or "about", none of the menu features seem to work. I rea ...

Building a React Typescript service with axios functionality

When creating a service and calling it from the required functional component, there are two different approaches you can take. 1. export const userProfileService = { ResetPassword: async (userId: string) => { var response = await http.get ...

retrieve Angular data across components using Input

When using fetch to make a request to the reqres api users in app.component, I then share the data with its child component (hello.component) via Input. While I am able to get the correct user names in the child template, I encounter an issue when trying t ...

Utilize Vue.js to easily upload images alongside form input fields

I have recently started a small project with Vue Js. I am trying to incorporate an upload file option in my contact form. Due to the numerous input text fields, I am using serialize for the form. However, I am facing issues with the append function. How ca ...

Issue with React occurring when attempting to delete an input component

I seem to be facing a challenge that I can't quite figure out whether it's related to React or not. To help illustrate the issue, I've created a simple example outside of my project: https://codepen.io/as3script/pen/VMbNdz?editors=1111 Wit ...

What is the process for inserting or removing a row with Javascript?

Currently, I am in the process of working on some HTML/PHP code which is displayed below. <h3 style="text-align:center;margin-top:45px;">Sitting Days</h3> <div class="sitting-days" style="display:flex; justify-content:center; margin-bottom ...

detecting key presses on documents using javascript

I'm having trouble capturing document-level key press events on a webpage. I've tried using the following code: $(document).bind('keydown', 'a', keyevent_cb); It works fine in IE, but it's not consistent in Firefox. I&a ...

Combine a string and integer in JavaScript without using quotation marks between them

Is there a way to concatenate a string and an integer in JavaScript without getting the ": Here is the code snippet: "<agm-map latitude=" + response.latitude + " longitude=" + response.longitude + "></agm-map>"; What it currently results in: ...

Unbinding or undoing an 'onclick' event when another 'onclick' event is triggered

I am facing an issue where clicking on elements with 'onclick' functions works as expected, but when I click on a different element with another 'onclick' function, the first one remains active. What I actually want is for the previous ...

Attention: React is unable to identify the `pId` property on a DOM element

After removing the span tag below, I noticed that there were no warnings displayed. <span onClick={onCommentClick} className={'comment'}> <AiOutlineComment className={"i"} size={"20px"}/> Co ...

The error message "Error: cannot read property ‘setDirtyAttribute’ of null" may be encountered when attempting to use the method YourModel.create({...}) in ember-typescript-cli

Encountering the error cannot read property 'setDirtyAttribute' of null even when using YourModel.create({...}) in ember-typescript-cli to instantiate an EmberObject. Model: import DS from 'ember-data'; import {computed} from "@ember/ ...

Delete a particular table while utilizing $.fn.DataTable.tables()

On a single page, I have several tables that need to be removed when the user decides. My approach was to utilize let table = $.fn.DataTable.tables() table[i-1].destroy(); This code is aimed at obtaining an array of all the tables and subsequently destroy ...

When using the `Document.write()` method, an error is returned stating, "Uncaught TypeError: Cannot read property 'document' of null"

I am currently integrating Angular2 into a website as the front-end framework, and it will be displayed on another website using an iframe. When working with the HTTP post method, I am able to receive a JSON response. Here is the API Post method that retu ...

"I am trying to figure out how to set a link to an image using JavaScript. Can someone help me

I need help figuring out how to insert an image or gif file within two inverted commas '' in this line of code: _("status").innerHTML = ''; (line number 13 in the actual code) Your assistance with this question would be greatly appreci ...