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

Using the novalidate attribute in Angular 4.0.0

Since migrating to angular 4, I have encountered a peculiar issue with my template-driven form. The required attribute on the input field appears to be malfunctioning. It seems like the form has the novalidate attribute by default, preventing HTML5 validat ...

Transform User's Regex Output into Uppercase

My nodejs program allows users to input text and apply their own regular expressions for editing. I want users to have the option to capitalize or lowercase text as well. For example, if a user enters "StackOverflow is great!" with the regex (.) set to be ...

The Vue Good Table seems to be experiencing issues with the filterDropdownItems returning inaccurate values

filterDropdownItems: [ {'value': 'active', 'text': 'Active'}, {'value': 'inactive', 'text': 'Inactive'} ] Upon selecting the Active option, it seems to also displaying t ...

What steps can be taken to disable Angular's automatic trimming of fields?

Is there a global way to prevent Angular from automatically trimming input fields throughout the entire application? I know that I can avoid it for specific fields using the ngTrim directive, but it's not ideal to add this directive to every text fiel ...

The synergy between HTML and JavaScript: A beginner's guide to frontend coding

I have primarily focused on server-side development of enterprise applications (Java EE, Spring framework). However, I am now exploring client-side technologies for better understanding (not necessarily to become an expert). I have studied HTML and CSS th ...

How to have multiple versions of grunt coexisting on a single machine

I am involved in two different projects that have unique requirements for Grunt versions: Project A specifically needs Grunt v0.3.2 Project B requires Grunt v0.4.1 Both of these projects are managed in separate workspaces. Currently, I have Grunt v0.4. ...

Check out the latest enhancements to React and Flask Fullstack right from your web browser

Recently, I ventured into the world of React and Flask development by following a tutorial found at this link. After completing the example fullstack website project, I realized that my code mirrored exactly what was provided by the author on their Github ...

Using NodeJS to convert a Base64 string into a JPEG image with the help of either NodeJS or

I have successfully stored a JPEG image in my MySQL database using the longblob format. Now, when I retrieve the longblob data, I am only getting a base64 string. How can I convert this base64 string back to a readable JPEG image using MySQL or Node.js? B ...

"Error: Trying to access the 'get' property of an undefined object," Axios, Vue.js

I encountered a peculiar error with Vue while attempting to access an API using axios. The error message reads "TypeError: Cannot read property 'get' of undefined" <template> <div class="home"> <h1>{{ msg ...

Modifying the $scope within a controller

I need to update the $scope within the controller based on the object that is being clicked. The current code looks like this: var blogApp = angular.module('blogApp', ['ngSanitize', 'ngRoute']); blogApp.controller('blog ...

Enhancing functionality with the power of VueJS in Laravel development

Embarking on a new large-scale application, I decided to explore the VueJS + Laravel combination after hearing rave reviews. I delved into Laracasts' Learn Vue 2: Step By Step series and various tutorials to grasp the inner workings of this setup. Ho ...

Is there a way to ensure that the await subscribe block finishes before moving on to the next line of code?

My goal is to utilize the Google Maps API for retrieving coordinates based on an address. In my understanding, using await with the subscribe line should ensure that the code block completes before moving on to the subsequent lines. async getCoordinates ...

Upon calling the createModalAddPost() function, a single window is triggered to open

Hey there, I'm having a JavaScript question. So, I have a panel that opens a window, and it works fine. But the issue arises when I close the window and try to open it again - it doesn't work. I have to reload the page every time in order to open ...

Divide a SINGLE BACKGROUND IMAGE in HTML into two separate links of equal size, one at the top and

As a beginner in HTML, I am trying to find a way to divide a background image into two equal sections without using image mapping. I attempted to split the links by setting the style to 0% and 50% to designate the top and bottom halves, but unfortunately, ...

Finding the difference or sum within an array to identify the two numbers that produce a new array

In order to clarify, I am looking for a method to identify the two smallest numbers in a sorted array that will result in a specific number when subtracted. The process can be broken down into the following steps: Iterate through the array and designate ...

What could be causing the lack of updates for a watched object in vue?

Although there are many similar questions on this topic, mine has a unique twist. After delving into reactivity in depth, I feel like I have a solid grasp of the concept. However, one thing continues to baffle me: Summary: Why does a watched property det ...

Can you provide a list of factors that influence coverage? Additionally, is there a specific algorithm available for calculating

As part of my Angular project, I am currently focusing on writing unit test cases using the Jasmine Framework and Karma. To ensure thorough testing coverage, I am utilizing Coverage-html (Istanbul). When it comes to coverage, there are several important t ...

Failed to load JSON data from the factory

Recently, I started learning AngularJS and have been struggling to fetch JSON data from a factory. The error message I keep getting is not very helpful: TypeError: Cannot read property '1' of null This is the module I am working with: var app ...

Ways to extract the id after clicking

In my code, I have a query called snapshot.forEach that functions similarly to a for loop in looping through all of my Firebase data and displaying it with a div tag containing a click event. When another user clicks on this div tag, the event will retriev ...

Unexpected Results from WordPress Ajax Request

Currently, I am utilizing the snippets plugin in conjunction with Elementor. To implement an ajax function as a snippet, I have set it up like so: add_action( 'wp_ajax_get_slug_from_id', 'get_slug_from_id' ); add_action( 'wp_ajax_n ...