Managing and updating arrays in VueJS2: Conditionally push new items and update only if their properties have changed

I am currently facing an issue with my form where each time a user updates a value in an input field, a new array element is created and added to the form results. I'm looking for a way to update the properties of the existing array element without creating a new one. How can I achieve this?

For instance, when editing the fields in the form below, it creates a new array element every time instead of updating the name and iso6393Char3Code properties:

[
  {
    "P_uniqueID": 16858,
    "name": "Badakhshān",
    "iso6393Char3Code": "fas"
  },
  {
    "P_uniqueID": 16859,
    "name": "Badakhshān",
    "iso6393Char3Code": "pus"
  }
]

The current behavior is resulting in multiple duplicate array elements being created as shown below:

[
  {
    "P_uniqueID": 16858,
    "name": "Badakhshānsss",
    "iso6393Char3Code": "fas"
  },
  {
    "P_uniqueID": 16859,
    "name": "Badakhshān",
    "iso6393Char3Code": "pus"
  },
  {
    "P_uniqueID": 16858,
    "name": "Badakhshānsss",
    "iso6393Char3Code": "fas"
  },
  {
    "P_uniqueID": 16858,
    "name": "Badakhshānsss",
    "iso6393Char3Code": "fas"
  },
  {
    "P_uniqueID": 16858,
    "name": "Badakhshānsss",
    "iso6393Char3Code": "fas"
  }
]

You can view the Codesandbox example here: https://codesandbox.io/s/interesting-haze-f7kl4?file=/src/components/ISOAdminDivForm.vue

Answer №1

To correctly update values in an array of objects, you should assign the values directly to the object rather than pushing a new object onto the array.

language(x) {
  // this.formValues.push(x);
  let el = this.formValues.find((e) => e.P_uniqueID === x.P_uniqueID);
  if (el) {
    Object.assign(el, x);
  } else {
    this.formValues.push(x);
  }

  this.$emit("languages", this.formValues);
}

View this codesandbox for a working example.

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

Building a JavaScript application with Node.js and MySQL to seamlessly interact with both offline and online databases

As I develop a JavaScript web-app, my plan is to utilize Node.js for connecting the app with an existing MySQL database. My initial question pertains to the structure of the Node code: should it be written in the same .js file as my application or kept se ...

Adding a plethora of HTML using jQuery

Struggling to create a single-page website, I've found myself relying heavily on jQuery's .append function. But surely, there has to be a more efficient method for appending large chunks of code (like tables, graphs, etc.) onto a page. Take this ...

What could be the reason behind the malfunctioning of my three.js lighting system?

I am struggling to identify the issue with this code snippet (http://jsfiddle.net/resistdesign/s6npL/). Despite referencing the documentation and some examples, the lights don't seem to be functioning as expected. var camera, scene, renderer, geometr ...

Troubleshooting Problem with Padding in ion-content for Ionic Angular

I am currently developing my inaugural Ionic application. The initial template I utilized was the rudimentary sidemenu layout. $ ionic start myApp sidemenu Afterwards, I crafted a straightforward page featuring a list which appears as follows... <ion ...

IE is failing to display the textarea, but it is successfully getting submitted

I've written a function in jQuery and JavaScript that generates a form element: createEmail: function(title){ var $emailForm = $('<form>',{action: 'sendEmail.php', id: 'emailForm'}); var $table = $( ...

Encountering a 'unknown column' error while using MySQL on a Windows operating system

A query is being executed on Node.Js with MySQL, resulting in the following: SELECT COUNT(DISTINCT t.uid) AS usersCount, COUNT(*) AS workingDaysCount FROM ( SELECT d.date, u.id AS uid, CASE TIMESTAMPDIFF(day, SUBDATE(d.date, WEEKDAY(d.date) ...

Retrieving previous data following an AJAX request using the GET method in Laravel 5.5

I have encountered an issue while using two ajax calls on a single page. On one side, I am making an ajax post request to store data and submit color in a database called "color_store." On the other side, I am trying to retrieve all the colors from that ta ...

Monitoring separate upload progress within $q.all() in AngularJS

I recently started using the angular-file-upload module created by danialfarid (https://github.com/danialfarid/angular-file-upload) and I must say, it's been a great experience so far. After successfully integrating it into my wrapper service for RES ...

Converting Axios URL Parameter to Array of Strings in ExpressJS

How to Send a GET Request using axios: await this.client.get('/endpoint', { params: { query: ['max', 'kevin'] } }) This will result in a URL that looks like this: Request GET /endpoint?query[]=max&query[]=kevin Any sugge ...

Tips for executing JavaScript code within a component

Looking to incorporate a parallax effect into an HTML element in my template. Have the code written, but uncertain of where to place it so that it runs each time the page is scrolled. let pos = document.body.scrollTop; document.getElementById('parall ...

Managing the uploading of files when a new property is included directly from the JavaScript File Object

When processing files using the POST method, I am able to access the default information such as name, type, size, tmp_name, and error through PHP. However, the file being sent contains additional data that I need PHP to extract. For instance, in the scre ...

Is there a way to trigger a function for both a left and middle click at the same time?

Check out this code snippet: $('a').on('click', function(){ myfunc($(this)); }); function myfunc(el){ console.log('Either left or middle click clicked on the link'); } a{ cursor: pointer; } <script src="https://aj ...

Mastering Vue Transitions: The Ultimate Guide to Creating a Seamless One-Time Animation Experience

I'm currently working on a Vue app for taking notes. The note being edited is automatically saved every few seconds. After each autosave, I want to display a brief message at the bottom of the screen that says "Note Saved". This message should fade in ...

Difficulty with info window within a for loop

I am currently working on implementing multiple info windows for markers. I found an example on Stack Overflow that I am trying to follow. Despite not encountering any errors in the console, the info windows do not appear as expected when clicking on the m ...

Storing input data in a JavaScript array instead of sending it through an AJAX request

I've been grappling with this issue for quite some time now, and I just can't seem to wrap my head around it. While there are a few similar solutions out there, none of them address my exact problem. Here's the scenario: I have a form where ...

Creating a dynamic div with various paragraphs using only Javascript

My goal is to dynamically generate paragraphs with their respective icons inside individual div elements. For instance, if the service API returns 30 items, I will create 30 div elements with the class "tile". However, if only one item is returned, then I ...

Unable to choose radio button again

Check out this fun web quiz I created! I'm having some trouble with the back button functionality. Whenever a user clicks back, I want to restore their previous choice but for some reason it's not working as expected. Take a look at my go_back ...

javascript function not being invoked

Currently, I have incorporated the following HTML <html> <head> <Title>EBAY Search</title> </head> <script language="JavaScript" src="ajaxlib.js"></script> <body> Click here & ...

How can one transfer information from a client to a server and complete a form using JavaScript?

Can the information be transferred from a client to the server using just JS, then fill out a form on the server, and finally redirect the client to view a pre-filled form? I am considering utilizing AJAX to send a JSON object, but unsure if it will be s ...

Issue with AngularJS: Controller unable to access property of ng-model object

I am looking to create a reusable controller that can be used by multiple views. This controller will essentially serve as a template. The issue I'm facing is with setting up simple validation. The problem lies in the fact that the properties set in ...