Unable to update a single object within an array using the spread operator

I am currently working on updating an object within an array and have encountered some issues. In my initial code, I successfully updated a specific property of the object inside the array like this:

var equipment = this.equipments.find((e) => e.id === this.currentItem.id);

// this property is getting updated successfully in the array
equipment.countryId = this.currentItem.countryId;

However, since the object has many properties, I attempted to use the spread operator to fully copy the object and update it with new values:

var equipment = this.equipments.find((e) => e.id === this.currentItem.id);
equipment = { ...equipment, ...this.currentItem };

Unfortunately, this approach did not work as expected. It seems that the spread operator creates a new object instead of updating the existing one in the array.

This raises the question: is there an alternative method to update all properties of an object with new values without explicitly defining each property?

Answer №1

Perhaps the reason is that when using the spread operator, a completely new object is created instead of updating the existing one?

A solution would be to return a new array and replace a single element by utilizing array.map:

this.equipments = this.equipments.map(equipment => {
    if(equipment.id === this.currentItem.id){
       return { ...equipment, ...this.currentItem };
    }
    return equipment;
});

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

While attempting to send a GET Request in Angular, access to XMLHttpRequest has been denied due to CORS policy restrictions

I am attempting to establish a GET method for my PHP API. Here is the code snippet I am using: export class PerfilComponent { perfil: any; constructor(private http: HttpClient) { } ngOnInit() { const token:string | null = localStorage.getItem(&ap ...

What is the best way to convert a JSON object back into an object with its own set of methods?

Currently, I have a JavaScript object with multiple methods attached via prototype. When I serialize the object to JSON, only the property values are saved, which is expected. It wouldn't make sense to save the methods as well. Upon deserialization ...

Error: The class you are attempting to access is

Currently, I am utilizing Vite.js along with TypeScript. My TypeScript file is located in 'src/vmodel/VGraph'. Within the index.html file, I import the aforementioned file as follows: <script type="module" src="/src/vmodel/VGrap ...

Inconsistencies in latency experienced when making calls to Google Sheets V4 API

Recently, I've been encountering latency issues with the following code: var latency = Date.now(); const sheetFile = await google.sheets({version: 'v4', auth}); var result = await sheetFile.spreadsheets.values.get({spreadsheetId: shee ...

What is the best way to include and delete several images on a canvas?

Recently, I've started working with canvas in HTML5 and I'm tasked with creating a paint application. One of the features I need to implement is the ability to dynamically add selected images to the canvas as the mouse moves, and then have the fu ...

JavaScript encountered an unexpected symbol, specifically the "=>" token

I encountered an issue while attempting to create a JavaScript function for deployment on Firebase: Error Message: Parsing error: Unexpected token => Here is the code snippet: exports.sendFriendRequest = functions.firestore.document("requests/{rUi ...

Tips for real-time editing a class or functional component in Storybook

Hey there, I am currently utilizing the storybook/react library to generate stories of my components. Everything has been going smoothly so far. I have followed the guide on https://www.learnstorybook.com/react/en/get-started and added stories on the left ...

Managing multiple sets of radio buttons using the useState hook

Within my renderUpgrades-function, I handle the options of an item by including them in radio-button-groups. Each item has multiple options and each option has its own radio-button-group. Typically, a radio-button-group can be managed using useState, wit ...

Issue when retrieving child elements in Next.js server-side component

"use client"; -- Imports and interfaces const SubscriptionDataFetcher: React.FC<SubscriptionDataFetcherProps> = ({ children }) => { const [data, setData] = useState<SubscriptionData>({}); -- Functions return <> ...

Show a specific form field based on the chosen option in a dropdown menu using Angular and TypeScript

I am looking to dynamically display a form field based on the selected value from a dropdown list. For instance, if 'first' is chosen in the dropdown list, I want the form to remain unchanged. However, if 'two' is selected in the drop ...

Changing Images with Jquery on Click Event

This section of the HTML document contains an image link that is designed to switch between two images when clicked. The images in question are timeline-hand and hand-clicked. Clicking on the image should change it from one to the other and vice versa. Ho ...

Using Slick.JS to Sync Navigation with Main Slider, Automatically Resetting to First Slide

I have a question about the functionality of the Slick.JS plugin that I'm using. In my project, I have two carousels with five slides each. The top carousel displays one slide at a time, while the bottom carousel shows all five slides concurrently. My ...

Is there a way to use Regex to strip the Authorization header from the logging output

After a recent discovery, I have come to realize that we are inadvertently logging the Authorization headers in our production log drain. Here is an example of what the output looks like: {"response":{"status":"rejected",&quo ...

React.js - "Encountered error: Unable to access 'map' property of undefined variable"

I've tried various methods I found through searching, but none of them seem to be working. Why is it still showing that map is undefined? import TextField from '@material-ui/core/TextField'; import Autocomplete from '@material-ui/lab/A ...

Finding the main page URL using PHP within a JavaScript include: A comprehensive guide

I am facing an issue where I have a page with a header include that needs the phone number to change only if the filename of the current page contains a specific word. Typically, for a change outside of an include, the following code would suffice. <? ...

The values of React children props will always remain consistent

While attempting to incorporate an ErrorBoundary HoC component for error handling following the guidelines from React16 documentation, I designed the ErrorBoundary component as a PureComponent. It became apparent that the children props remained consistent ...

Generating separators in every third row using an array of card elements

https://i.stack.imgur.com/PIMR2.png Hey everyone, I'm working on creating a Divider for every row of 3 items. Currently, my setup only handles two sets of rows, but there could be an unlimited amount of rows that need this divider. I am using slice t ...

Can Selenium successfully scrape data from this website?

I am currently attempting to extract Hate Symbol data (including the name, symbol type, description, ideology, location, and images) from the GPAHE website using Selenium. As one of my initial steps, I am trying to set the input_element to the XPATH of the ...

How to make a POST request with custom headers in NestJS

Has anyone successfully sent a Post request using Nestjs to a 3rd party API that needs authorization through a client-key and secret? I am looking for guidance on how to include headers in the request, ideally using axio's HttpService. ...

Unable to locate the 'react-native' command, attempted various fixes but none were successful

Working on an older react native project that was functioning perfectly until I tried to pick it back up and encountered a problem. https://i.stack.imgur.com/1JUdh.png This issue revolves around the package.json file. https://i.stack.imgur.com/v6ZEf.png ...