How can I update a specific element within an array of objects in JavaScript based on its reference rather than its index position?

I am dealing with multiple arrays of objects

x=[ {a:1}, {b:2}, {c:3}, {d:4} ]

y=[ {e:5}, {f:6}, {g:7}, {h:8} ] (etc)

and I have a list of references pointing to the objects I need to replace.

Instead of having an index into the array, I hold references to the items I want to update

An example reference might look like this: r=x[2] or r=y[0]

How can I utilize this reference to substitute the element within the original array regardless of which array it belongs to?

Trying to do this directly will not work: r = {a:'new'} , as it just modifies r, NOT the array's element

This method is not convenient either: r.a='new' , since my objects are complicated, comprising numerous properties, and I prefer not updating them one by one.

Many thanks!

Answer №1

When dealing with objects that are simply plain Objects (or at least of a similar type), it is possible to delete all properties and replace them with new ones:

const updateProperties = (target, source) => {
    Object.keys(target).forEach(key => {
        delete target[key];
    });

    Object.assign(target, source);
};

updateProperties(obj1, {v: 'new'});

However, although this method works, it might not be the most efficient solution. It is recommended to consider using indexes in the array instead.

If the objects have the same structure (i.e. always contain the same properties), a better approach would be to take advantage of this by using Object.assign() for updating multiple properties simultaneously:

Object.assign(obj1, {v: 'new'});

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

Utilizing Ajax and jQuery to extract information from an XML file based on an identification number

Currently, I am looking for a way to showcase a specific product with its description from my XML file by using the product's ID. The structure of my XML file is shown below: https://i.sstatic.net/wFWgW.png Below is the JavaScript code I am using: ...

Limit the number input to only allow values between 0 and 100

I am utilizing the Number input component from MUI, which includes Increment and Decrement buttons for adjusting numbers. Is there a method to limit the input to only accept values ranging from 0 to 100 ? Additionally, how can I decrease the width of the ...

The Vue3 counterpart of vNode.computedInstance

I'm currently in the process of upgrading my app from Vue2 to Vue3, but I've hit a roadblock when it comes to dealing with forms. For my form elements, such as FormInput, FormTextArea, and FormCheckbox, I have been using Single File Components ( ...

Updating Socket.io with multiple data emissions upon refresh or reload

I'm facing an issue that is very similar to this problem: https://github.com/rethinkdb/rethinkdb/issues/6503 Whenever I connect for the first time, it only logs once. Upon refreshing, it logs twice. Subsequent refreshes result in an additional log ea ...

Jquery click event functioning on one page but malfunctioning on another

On one page, the dropdown click function is working, but on another page, even though it's the same component and JavaScript file, it's not working. Here's the component: <li class="nav-item dropdown"> <a clas ...

When using Next.js and Express.js together, CORS error may occur, causing API queries to only function properly during build

I am currently working on a project that involves using Next.js for the front-end and Express.js for the back-end. Front-end Setup The 'pages' directory contains an 'index.js' file where I have implemented the following code snippet: ...

What is the functionality of the getBlock('meta') method within DocPad?

While transitioning a website from a different site generator to DocPad, I am currently exploring the capabilities of the getBlock('meta') feature. Understanding how to utilize getBlock('scripts') and getBlock('styles') was re ...

`html2canvas encountered an issue: Unable to locate a logger instance`

When I use html2canvas to render the same content repeatedly, I encounter an error about 5% of the time. It seems to be sporadic and I'm not sure why it occurs. What could be causing this unpredictable behavior? html2canvas.js:2396 Uncaught (in promi ...

Having trouble with script tag not loading content in Next.js, even though it works perfectly fine in React

Currently, I am attempting to utilize a widget that I have developed in ReactJS by utilizing script tags as shown below- React Implementation import React from "react"; import { Helmet } from "react-helmet"; const Dust = () => { ...

Next.js throwing an error: TypeError - attempting to read property 'map' of undefined

I am facing an issue with my Next Js project. I have implemented the backend logic to display data, but when I attempt to show all the data using the useEffect hook and the map function, I encounter the following error: TypeError: Cannot read property &apo ...

Stopping setTimeout when leaving the current page: Is it possible?

Good evening, I am looking for advice on how to cancel a setTimeout function when a user navigates to other pages (for example, by clicking other links or pressing the back button in the browser, but not by changing tabs). I have attempted to use the windo ...

Shifting hues of colors on website based on geographical location

Working on a new project, I encountered an issue with two elements sharing the same class but displaying different color shades. Has anyone experienced this before and knows what could be causing it? UPDATE Here is an excerpt of the code: The Class: .su ...

Storing Documents on Your Device

I've been working on a project to create a web page that provides links to online PDF files. When you click on these links, the file should be saved locally and its name/path added to local storage. I then aim to display all the saved files by iterati ...

Collecting information from JSON files

Within the cells of my calendar are placeholders for events, dates, participants, and descriptions. Now, I am looking to populate these placeholders with data previously stored using localStorage. Unfortunately, my current code is not achieving this. How ...

Utilizing the content of an HTML element within Ruby embedded code - a comprehensive guide

Below is the code snippet in question: <% @groups.each do |group| %> <tr> <td id="groupid"><%= group.id %></td> <td><a href="#dialog" name="modal"><%= group.title %></a></td> </tr> &l ...

When attempting to add an object to an array in a collection, there was an issue with

In my application, I am accessing a collection in Mongodb using ReactJS and mongoose. One of the properties in this collection is set to an Array type. When I add elements to this Array, they are successfully added but for some reason, the _id field that ...

Why is JavaScript globally modifying the JSON object?

I have a few functions here that utilize the official jQuery Template plugin to insert some JSON data given by our backend developers into the variables topPages and latestPages. However, when I use the insertOrHideList() function followed by the renderLis ...

The total number of items in the cart is experiencing an issue with updating

For a recording of the issue, click here: While everything works fine locally, once deployed to production (vercel), it stops working. I've tried numerous approaches such as creating a separate state in the cart, using useEffect with totalQuantity in ...

Are there any drawbacks to converting all instance methods into arrow functions in order to prevent binding loss?

What are the potential drawbacks of converting all instance methods into arrow functions to avoid the "lost binding" issue? For example, when using ReactJS, the statement onClick={this.foo} can lead to lost binding, as it translates to createElement({ ... ...

Is there a more efficient approach than array_walk that I should be using instead?

One of the arrays in my code is named "methods" and has the following structure: [0] => Array ( [id] => WWAM [title] => WWAM [cost] => 4.35 ) [1] => Array ( [id] => CNQM [title] => CNQM [cost] => 5.21 ...