Array automatically updates its values

....
import * as XLSX from 'xlsx';
...

I am currently parsing a .xlsx file in an Ionic 4 application.

showData() {
  let fileReader = new FileReader();
  fileReader.onloadend = (e) => {
    this.arrayBuffer = fileReader.result;
    let data = new Uint8Array(this.arrayBuffer);
    let arr = new Array();
    for (let i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
    let bstr = arr.join("");
    let workbook = XLSX.read(bstr, { type: "binary" });
    let first_sheet_name = workbook.SheetNames[0];
    let worksheet = workbook.Sheets[first_sheet_name];
    let rows = XLSX.utils.sheet_to_json<Income>(worksheet, { raw: true });

    this.allIncomesFromDocument = rows 
    this.Test(rows)    
  }
  fileReader.readAsArrayBuffer(this.file);
}

Test(rows){
  this.allIncomesFromDocument.forEach( v => console.log(v.quantity) ) // FIRST LOG

  rows.forEach( row =>{
    row.quantity = 0;
  })

  this.allIncomesFromDocument.forEach( v => console.log(v.quantity) ) // SECCOND LOG
}

The first log displays the following data:

8
7
5
9
2
etc.

This reflects the information extracted from the file initially.

However, despite not changing any values and simply repeating the same forEach loop, the second log instead shows:

0
0
0
etc.

Clearly indicating that the logs are entirely divergent.

Answer №1

By using the code

this.allIncomesFromDocument = rows
, you are assigning a reference to the data instead of making a copy.

So, when you update the quantity with row.quantity = 0;, you are actually modifying the reference and affecting both variables.

To ensure that you create a complete copy of the data, modify the code from

this.allIncomesFromDocument = rows
to
this.allIncomesFromDocument = JSON.parse(JSON.stringify(rows))
.

Answer №2

To ensure the original object is not mutated, you can assign two arrays in this scenario. One of the arrays should use Object.assign for this purpose. For example:

const items = [{item: "apple"},{item: "banana"},{item: "orange"}];

const allItems = items;

let newItems = items.map(item => {
  let newItem = Object.assign({}, item);
  newItem.quantity = 0;
  return newItem;
});

console.log(allItems);
console.log(newItems);

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

Step-by-step guide on updating a database using AJAX post serialization in PHP, jQuery, and JavaScript

I am facing an issue with updating my rooms table using the update query from serialize. Instead of saving all the data, it only updates the first row in the table. Here is my room list in the rooms table of my database: 1 Room1 Regular 2 Room2 ...

In what ways can we enhance the appearance of the show entries and make the font in Datatables larger?

Working on an HTML file that contains mainly tabular data. Utilized the styling features of Datatables, but looking to customize the color, border color, and size of the select icon next to the show entries option along with increasing the text. The German ...

Creating a Collection of Polygon "Pointers" in Python

Currently, I am creating animations that involve a large number of filled polygons. The process involves defining each polygon by copying vertices from a standard profile shape, transforming them into the correct locations on the figure, and using a plt.fi ...

Managing a database update when server actions involve various form types

My UI dashboard contains multiple forms like "edit title" and "edit description", each with just one input element. I am looking to streamline database updates and server actions in next js 14, utilizing useFormState on the front end. While I have achieve ...

Navigating to a new URL using window.location.href will seamlessly embed the new page within

I am new to JavaScript and I am facing an issue with my AJAX function. The function is supposed to navigate to a new URL, but instead of loading the new page separately as if the user had typed the URL, it gets inserted inside the same div where the button ...

Is there a way to reverse a string in Javascript without using any built-in functions?

I am looking for a way to reverse a string without using built-in functions like split, reverse, and join. I came across this code snippet on Stack Overflow (), but I'm having trouble understanding what the code does on the fourth line. I need more cl ...

javascript: unable to modify currentTime in <audio> tag

Struggling to create a progress bar for my HTML5 audioplayer and implement a function to change the playing track's time by tapping. I opted to use input[range], but encountering an issue where the current play time does not update when tapping on the ...

Uploading videos to a single YouTube channel using the YouTube Data API

I have been tasked with creating a node js app for a select group of individuals who need to upload videos. However, our budget is quite limited and we are unable to afford cloud storage services. I am curious if it would be feasible to create a key syste ...

Controller unable to update AngularJS view

As the title suggests... I'm facing a challenge with this code snippet: (function(angular) { 'use strict'; angular.module('app', []) .controller('ctrl', ['$scope', function($scope) { $scope.ini ...

"Performance issues with Three.js due to too many textures in 200

I have been experimenting with three.js for a few months now. Recently, I began working on a project involving a 3D webgl product catalogue where we store base64 images in the browser's indexeddb and create the catalogue upon app load. The issue arise ...

Obtain the ID of element 1 by clicking on element 2 using JQuery

In the world of javascript/jquery, When button1 is clicked, we can get its id like this: var button1id = $(this).attr("id"); If button2 is clicked, how do we retrieve button1's id? This brings us to the question: How does button2 access the i ...

Using AngularJS ui-router ui-sref results in the error message "Uncaught TypeError: Cannot read property '0' of undefined."

I am currently working on an angularJS component that utilizes ui-router with 2 straightforward route states. export default function Routes($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('details', { ...

Incorporating a Layered Div onto a Presentation Slider

Over at , we have a slider featured on the homepage. I am attempting to place a div ABOVE the image but BELOW the text. Essentially, my goal is to add a semi-transparent white overlay to enhance the image on the slider while keeping the text visible for b ...

Tips for removing "<li>" elements using JavaScript

My issue remains unresolved... I created a tree structure in MVC and added JavaScript code for expanding and collapsing the tree. However, after applying the code, my tree is not being displayed correctly. enter image description here In the image, you c ...

Ways to dismiss a Modal popup instantly without having to wait for an ajax response

I am currently facing an issue with sending email attachments through ajax. The process takes too long to send and close the email modal window. I am looking for a solution where the modal window closes immediately after clicking the send email button, all ...

I am curious how to utilize Puppeteer to iterate through an array of links, moving to the initial link, closing the tab, and repeating the process

In my current setup, the script navigates to the first link I specify in the following manner: (async () => { let funkoUrl = "https://www.cardboardconnection.com/brand/funko/funko-pop"; let browser = await puppeteer.launch({ headless: false, ...

The combination of Inline CSS and Bootstrap classes does not seem to be functioning properly

I'm new to web design and currently working on a website project. My concept involves hiding the #login-box when the user clicks on the login button, and displaying another element (.dashboard) in its place. Initially, I set the .dashboard class to ha ...

Is it possible to distinguish and identify each separate window when a user opens multiple instances of your site?

Has anyone explored the possibility of distinguishing between multiple windows a user may open on the same site? My goal is to assign the initial window the name "window1" and subsequent windows "window2" and so forth. Is there a method for achieving this ...

Learn how to eliminate all text characters from a string using jQuery, leaving only the numerical values behind

My webpage features a variety of different products, each with their own values. When trying to calculate the total sum of these products and display it in the shopping cart, I encountered an error displaying NaN. How can I remove this NaN from the strin ...

The jqGrid method is not supported on a Windows Server 2012, causing an error with the object's property

While the jq grid is working smoothly on the asp.net dev server, it encountered an error on IIS 8 (Windows Server 2012) with the message: Object doesn't support property or method 'jqGrid' JavaScript <script type="text/javascript"> ...