TypeScript maintains the reference and preserves the equality of two objects

Retrieve the last element of an array, make changes to the object that received the value, but inadvertently modify the original last position as well, resulting in both objects being identical.


    const lunchVisit = plannedVisits[plannedVisits.length - 1];

    lunchVisit.visitPoint.name = 'lunch';

    lunchVisit.lunch = true;

    lunchVisit.waypoint.estimatedArrival = plannedVisits[plannedVisits.length - 1].waypoint.estimatedDeparture;
    const lunchEndTime = new Date(plannedVisits[plannedVisits.length - 1].waypoint.estimatedDeparture);
    lunchEndTime.setHours(lunchEndTime.getHours() + 2);
    lunchVisit.waypoint.estimatedDeparture = lunchEndTime;
    console.log(plannedVisits[plannedVisits.length - 1])
    console.log(lunchVisit)
    plannedVisits = [...plannedVisits, lunchVisit];

Answer №1

By implementing the deep copy method, we were able to create a separate copy of the original object without retaining any references.

const lastVisit = cloneDeep(lastItemInArray);

function cloneDeep<T extends object>(original: T): T {
    return JSON.parse(JSON.stringify(original));
}

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

Adjust the colors of the borders upon clicking the button

Hello, I'm attempting to create a function where clicking on one button changes its border color to blue and changes the border color of all other buttons to orange. However, I'm encountering an issue where the border color for the other buttons ...

Adjust width based on value dynamically

I currently have a div that is sized at 250px, housing 3 child divs within it. My goal is for each of these 3 divs to dynamically scale based on their respective values, eventually reaching 100% width. This is the code snippet I am working with: <di ...

Processing a list in Angular using Observables

In my Angular12 application, I am fetching data from a Firebase Realtime DB using AngularFire. To streamline my code and ensure consistency, I have implemented a DAO service to preprocess the retrieved data (e.g., converting string dates to Date objects). ...

In what location can event listeners be found in npm packages?

For a while now, I've been immersed in the world of coding as I work on creating my very own IRC bot using nodejs. This project serves as an invaluable learning experience for me, and as I navigate through the process, I constantly encounter event lis ...

producing base64 encoding that results in a blank image

I have some code that is supposed to get an image from a video using canvas. However, when I save this base64 code into an image, I end up with a black image. What could be causing this issue? Here is my JavaScript code: var input = document.getElementBy ...

Overlapping Dropdown Javascript Menus

To achieve the desired effect in the header, I need to create two expandable dropdown menus for the first two titles. My coding experience is limited, especially when it comes to javascript and jquery. Currently, I have managed to create the effect for one ...

What is the best way to eliminate duplicate values from an Array in ReactJS?

Hi there, I'm new to JavaScript and React. I need some help with a project I found on the React blog. I want to try solving it in my own way. This is the content of todoList.js: const todoList = [ {category: 'Sporting Goods', price: &a ...

Verify if any choices are available before displaying the div block

I need to determine if there is a specific option selected in a dropdown menu, and then display a div if the option exists, otherwise hide it. I'm not just checking the currently selected option, but all available options. if (jQuery(".sd select opti ...

Issues with external javascript link functionality

I'm having trouble connecting my external JavaScript file to my HTML code. I'm attempting to concatenate two strings using an input function and then display the new string in the empty text field. What could be causing this issue? Appreciate an ...

A tutorial on ensuring Angular loads data prior to attempting to load a module

Just starting my Angular journey... Here's some code snippet: ngOnInit(): void { this.getProduct(); } getProduct(): void { const id = +this.route.snapshot.paramMap.get('id'); this.product = this.products.getProduct(id); ...

Switching between different elements in an array using React

I've got a collection of appointments and I need to create a React view that will show them one by one. Users should be able to navigate through the appointments using arrow buttons. Here's an example of what the data looks like: const arr = [ ...

Button click not functioning to switch the displayed image in Javascript

As a beginner in Javascript, I'm attempting to create a basic button in html that switches the originally shown image when clicked. Unfortunately, my current code isn't functioning properly. Could someone please assist me in identifying the mista ...

What is the best way to upload a file to Firebase Storage using React?

I am facing difficulty uploading a file to Firebase in order to retrieve its getDownloadURL. This is the code snippet I currently have: import React, {useState, useEffect} from 'react' import { Container, Button, Row, Col, Form, Alert } from &ap ...

Error in JavaScript goes undetected when utilizing asynchronous AJAX

Having recently started working with ajax and javascript, I find myself puzzled by the fact that my error is not getting caught when making an asynchronous ajax call. I did some research on a similar issue in this query (Catch statement does not catch thr ...

Exploring Reactive Programming with RxJS and organizing data into individual streams

As I delve deeper into working reactively with Angular 15 and RxJS observables for a UI component, my focus lies on subscribing to data solely within the component template (html). The data is fetched from an external system through a service. However, a c ...

Using the PUT method in combination with express and sequelize

I am having trouble using the PUT method to update data based on req.params.id. My approach involves retrieving data by id, displaying it in a table format, allowing users to make changes, and then updating the database with the new values. Here is the co ...

What could be causing the error I'm encountering while running the 'net' module in Node.js?

I am currently working with .net modular and have opened TCP port 6112. var net = require('net'); var server = net.createServer(function (socket) { //'connection' listener }); server.listen(6112, function () { //'listening ...

tips for implementing JSON loading in Ext JS

While attempting to load values from a web service, I encountered the following error message: "ChatStore.data.items[i] is undefined." The mapping code for extjs is as follows: ChatStore = new Ext.data.JsonStore({ storeId: 'ChatStore1' ...

What is the reason for Cypress choosing to omit specific commands?

The test below aims to scan and authenticate a QR code, then utilize the received authentication token. However, for some reason, the last two commands (.type) are not being executed. I've been stuck at this point for quite some time now. Any insights ...

Concealing URL in client-side fetch request within Next.js

A contact form built in Next.js makes use of the FormSubmit API to send emails upon clicking the submit button. Below is the code for the onSubmit handler: const handleSubmit = async (e) => { e.preventDefault(); const res = await fetch("https:/ ...