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

The option value in mat-autocomplete is not displaying correctly on IOS devices

When I click on the first option in the dropdown menu, it does not display the selected option in the field. However, when I select the second option, then the value of the first option appears, and when I choose the third option, the value of the second o ...

Refining the options in security question dropdown menus

Firstly: The title should mention filtering security options in dropdown lists, but it seems I'm restricted from using the term questions or question in the title. I came across this code example, but it appears to be outdated. Does anyone know why a ...

Learn the steps for filling the color area between two points in HighCharts

Is it possible to have a color fill between two points on an area chart when clicked? You can view the current chart here. $(function () { $('#container').highcharts({ chart: { type: & ...

Attempting to implement endless scrolling functionality using rxjs and angular 2 framework

I'm struggling to understand how I can incorporate stream data into my infinite scroll feature. First, I define my observable variable and page offset: products$; offset: number = 0; Next, I create an observable using one of my services: this.prod ...

How can I retrieve all the recipes associated with a specific user (id) using ASP.NET Core 3.1.1 MVC and Angular?

Currently delving into ASP.NET MVC, I am immersed in building a single-page application using ASP.NET Core 3.1.1 with APIs. Within my User.cs file, there exists a collection of the user's Recipes. Specifically, within my User class, there is a prope ...

Can someone guide me on incorporating bluebird promises with request-extensible?

I'm interested in utilizing the bluebird library to create a promise-based asynchronous web client. Currently, I have been using the request-promise package for this purpose. To get started, I simply include the following lines of code at the beginnin ...

Is it possible to activate the onChange event when the input value is being modified by the state with information obtained from a fetch

Currently, I am successfully fetching data from an API and storing it. However, I now want to incorporate a functionality where a user can paste a website URL into an input box, click a button, and then display the results in a return div UI. I am struggli ...

Securing RESTful APIs with stringent security measures

Lately, I've been delving into using modern front end technologies such as React and Angular. This has led me to explore tools like JSON Server for simulating restful database interactions. I've noticed that most REST APIs require authentication ...

The content section sits discreetly behind the sidebar

Upon loading my Bootstrap 5 webpage, the toggle button successfully moves the navbar and body section to show or hide the full sidebar. However, an issue arises where the body section goes behind the sidebar when using the toggle button. Below is a portio ...

Efficiently configuring Angular 2 with ng-bootstrap

Hi there, I am currently diving into the world of Angular and Bootstrap, while also exploring node js. My goal is to create a solid foundation using the webpack starter kit available at this link: https://github.com/AngularClass/angular2-webpack-starter ...

How can we troubleshoot webdriver cucumber when test steps are skipped due to passed arguments?

Greetings! I have a feature file outlined below in my cucumber webdriver test project: # language: en Feature: Simple Test, Int and Prod Origin vs non origin checks Simple cloud environment Checks @javascript @EnvCheck Scenario: Check Env TEST Orig ...

Utilize a for loop in Vue.js to save a fresh array of objects in a structured format

Trying to achieve the following using Vue: I have two JSON objects that provide information on languages and the number of inputs per language. Using nested loops, I display all the inputs. My goal is to create an object for each input with additional det ...

My ng-view html is unexpectedly displaying as plain string. What steps should I take to resolve this issue?

Why is my ng-view HTML displaying as plain text? How can I resolve this issue? I have encountered an error, here is the screenshot for reference: Unfortunately, I am unable to upload images at the moment. ...

When using an Angular2 application that relies on an external reference to Auth0Lock, the application encounters a NotFound error when executed

For my latest project, I decided to create an app using angular2-seed as a base. Everything was going smoothly until I tried deploying the production build on an Azure website. To my surprise, I encountered an issue when trying to load the page: > Refe ...

Determine user connectivity in Angular 4 using Firebase

My current setup involves using Firebase for authentication with Google. However, I am encountering an issue where upon refreshing the page after being connected, I am unable to retrieve the Session/CurrentUser information. firebase.auth().onAuthStateChan ...

Unable to iterate over an array within a single file Vue component

I created a vue.js app utilizing single file components. In the data section, I initialized an empty array like this: data: function () { return { teamKeys: [] } }, Next, I populate this array by pushing values into it within one of my methods: ...

Postpone the execution of the page controller until all necessary initial data has been collected

My Single Page Application (SPA) is in need of some initial data fetched from the server, such as user login status and permissions. However, I want to defer loading the page until this vital information is retrieved to avoid any issues with incomplete dat ...

Updating state before and after making an API request

I have implemented an asynchronous function with prevState in my code. The purpose of using prevState is twofold: 1) updating a deeply nested object and 2) sending data to an API based on the current state. Asynchronous programming is utilized for the API ...

Unable to generate this QUIZ (JavaScript, HTML)

Hi there, I'm working on a sample quiz and having trouble displaying the result. As a coding newbie, I could really use some help. In this quiz, users answer questions and based on their responses, I want to display whether they are conservative, agg ...

When attempting to utilize VueJs v-bind:type on an input element, it appears to be ineffective when the type property name is

Code: <!DOCTYPE html> <html> <head> <title>Creating a Vue app</title> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3046455570021e061e0100">[ ...