Even after setting a new value to a variable in Vue, it may still reference the old

init(){
  this.unsortedList = this.selectedVoucher.approvalStepList;  // list in original order

  this.sortedList = this.unsortedList
    .sort(function(a,b){
      if (new Date(a.createDate) < new Date(b.createDate)) return -1;
      if (new Date(a.createDate) > new Date(b.createDate)) return 1;
      return 0;
  });

  this.sortedApprovers; // list now sorted

  const approver = this.selectedVoucher.approvalStepList.sort(function(a,b){
    return  new Date(a.createDate) - new Date(b.createDate)
  })[0].step==2;

  this.revertedList = this.sortedApprovers  // list no longer in sorted order, even though not explicitly changed

Answer №1

The reason for this issue is due to the initial assignment of the pointer to

this.selectedVoucher.approvalStepList
at the start of the code:

this.approvalStepList = this.selectedVoucher.approvalStepList;  // not sorted

Instead, it would be better to assign a copy of the array using the spread operator like this:

this.approvalStepList = [...this.selectedVoucher.approvalStepList];

The problem arose because without making a clone, but only assigning a variable, both values were linked together as they referenced the same object in memory. Any changes made to one would affect the other. By creating a copy, this issue can be resolved. Here's a simple example to explain this:

https://i.sstatic.net/tjLbH.png

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

Create an interactive webpage that automatically generates new HTML elements after retrieving JSON data from a Web API during page load

I am currently in the process of developing a hybrid Android App using Phonegap/Apache Cordova. The main function of my app is to retrieve data from my web API, which is being served through JSON. I have implemented the following code snippet for this task ...

Storing user credentials in Firestore after registration - best practices

Hi, I need some assistance with storing user credentials in Firestore after they sign up. Unfortunately, I keep encountering the following error: Invalid collection reference. Collection references must have an odd number of segments, but userDatabase/QMJ ...

A guide on incorporating a customized Google map into your website

Recently, I utilized the Google Map editing service from this site: https://developers.google.com/maps/documentation/javascript/styling This link provided me with two things: 1. A JSON code 2. The Google API link However, I am unsure about how to incorpo ...

Encountered an issue with the property 'push' not being defined

Here's the schema for my mongoose model in JavaScript: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const CartSchema = new Schema({ userID: String, items: [{ itemID: String, quantity: Number }] }); modul ...

How can I use the select2 jQuery plugin with the tags:true option to ensure that selected choices do not appear again in the dropdown menu?

Transitioning to select2 for tagging from a different plugin, I'm facing a gap that I need to address in select2's functionality. Let's consider an example. Suppose my list of choices (retrieved server-side via Ajax request) is: "Dog", "Ca ...

Output a variable that is generated from invoking an asynchronous function

I'm currently in the process of developing an application that is going to leverage the capabilities of a SOAP server through the use of the https://github.com/vpulim/node-soap module. One of the main challenges I am facing is how to efficiently crea ...

What methods can I use to ensure this car rotates smoothly, whether or not I combine meshes in Three.js?

My current challenge involves creating a car game here. The issue is that although the wheels are rotating, they are not moving in sync with the car itself. Here is the code snippet from my car.js file: export function createCar(x, y, z, color) { const ...

What is the best way to combine Bootstrap and custom CSS, specifically the home.module.css file, in a React project?

I'm currently experimenting with utilizing multiple classes to achieve an elevated button effect and a fade animation on a bootstrap card. Here's the code snippet I've been working on: import Head from 'next/head' impo ...

Upon clicking the button, provide the client with the Cloudinary link

In my Next.js project, I am using Cloudinary to generate secure URLs for images. The URL is stored in the variable result.secure_url within my app/page.js file. The button functionality is defined in app/components/Cloudinary.js and imported into app/pag ...

What is the best way to display HTML file references in TypeScript files using VSCode when working with Angular templates?

Did you know that you have the option to enable specific settings in VSCode in order to view references within the editor? Take a look at the codes below: "typescript.implementationsCodeLens.enabled": true, "javascript.referencesCodeLens.enabled": true I ...

Hermes, the js engine, encountered an issue where it was unable to access the property 'navigate' as it was undefined, resulting

Whenever I switch from the initial screen to the language selection screen, I encounter this error and have exhausted all possible solutions. I attempted to utilize "useNavigation" but still encountered errors, so I resorted to using this method instead. T ...

Need assistance with jQuery AJAX?

Hey there, I'm a new member and I've gone through the different Ajax Help topics but still can't figure out why my code isn't working. Here's what I have: $(document).ready(function(){ $.ajax({ type: "GET", ur ...

Utilize utility functions within the onCreated lifecycle event in Meteor

Here is my current setup: Template.myTemplate.helpers({ reactiveVar: new ReactiveVar }); How can I initialize reactiveVar within the onCreated function? Template.restaurantEdit.onCreated(function() { // I want to initialize helpers.reactiveVar here ...

Avoid having logs displayed on the server end when utilizing console.log commands

Being new to JavaScript and Node.js, I am attempting to have my application output logs on the server side. getUser.onclick = function () { console.log('Server running at http://127.0.0.1:1337/'); var req = new XMLHttpRequest(); r ...

Issue with esbuild not executing within docker compose configuration

Currently, I am new to using esbuild and struggling to set up a script that can watch and rebuild my files. Additionally, I need this functionality to work within a docker environment. Within my package.json file, the following scripts are defined: " ...

How can we style the <a> link once it has been downloaded?

Is there a way to change the color of a download link after it has been clicked on? I've attempted using the visited attribute, but it only seems to work with regular links and not with download documents: Appreciate any help ...

Is Next.js compatible with CSS caching?

I'm currently working on a project with Next.js (version 12.1.0) and SCSS modules. I've noticed that my CSS seems to be caching extremely aggressively, requiring me to restart the server (npm run next dev) in order to clear it. Has anyone else en ...

Build an equilateral triangle with the power of three.js

I'm currently working on creating an equilateral triangle using three.js, but it seems like what I've created is a bit too tall. My vertices are defined as follows: new THREE.Vector3(0, 0, 0), new THREE.Vector3(4, 0, 0), new THREE.Vector3(2, 4, ...

I am having trouble with my jQuery wrap function and it is not functioning correctly

I'm having trouble with implementing the jQuery wrap function. (function ($) { $.fn.customWrap = function () { applyWrapper(this); return this; }; function applyWrapper($element) { var $input = $('<input&g ...

Utilizing Mongoose Schema Enums Alongside TypeScript Enums

In our Typescript-based NodeJs project utilizing Mongoose, we are seeking the right approach to define an enum field on a Mongoose schema that aligns with a Typescript enum. To illustrate, consider the following enum: enum StatusType { Approved = 1, ...