Manipulating objects within arrays in Typescript/Angular with a focus on copying

I'm currently facing issues with filtering an array using an HTML input. Here is the code snippet in question:

  ngOnInit() {
    this.dtoService.setJsonResponse();
    this.getPool();
  }

  getPool() {
    this.json = this.dtoService.jsonResponse;
    this.copyJson = Object.assign([], this.json);
  }

  filterArray(): void {
    this.json = this.copyJson;
    this.json.pools = this.json.pools.filter((e) => 
    e.name.includes(this.filter));
    console.log(this.copyJson);
  }

Although the filtering function works as expected initially, I noticed that when a character is removed from the input field, the search results don't update accordingly. It appears that the copyJson variable is also being modified, as when I print it out, it contains the same objects as the filtered json. This seems to be related to references - any ideas on how to solve this issue?

Answer №1

The issue arises from copying the reference, which leads to unintentional modifications in the source object (this.copyJson) whenever changes are made to this.json.

To resolve:

this.json = {...this.copyJson};

Answer №2

The reason for this issue is that you are performing a shallow copy of the this.json object and filtering a nested object json.pools.

To resolve this, it is recommended to create a deep copy instead. You can achieve this using lodash.cloneDeep: https://lodash.com/docs/4.17.10#cloneDeep

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

Reading JSON arrays with JQuery

I have a RESTful web service located at http:// localhost:8080/CRUDWebAppMavenized/persons that returns a JSON array. I am using jQuery AJAX to fetch the data and display it in an HTML table, but I'm having trouble getting it to show up properly. Belo ...

What is the best way to incorporate a dynamic background in NextJS using Tailwind?

I have a poster image that I want to use as a background image, fetched from MovieDb. I tried putting it inside the className like this: className={bg-[url('${path}')] h-screen bg-cover bg-center text-white border-b-8 border-b-solid border-b-sla ...

How can you connect a property to the output of a method in Vue.js when working with TypeScript and vue-property-decorator?

I'm working with a TypeScript single file vue component. I've encountered an issue where the template does not display the values returned by certain component methods. Here's a snippet of the template: <div class="order-items"> ...

react-router version 2.0 fails to direct traffic

I'm facing an issue with a piece of code that I have modified from the react-router project page. Despite my modifications, it doesn't seem to work as expected. Configuration In my setup, I have created several simple react components: var Ind ...

Error 401 received for CORS preflight in Angular 2 is invalid

I'm in the process of developing an application using Angular 2 and implementing an authentication service. However, when I try to make a request to my server, I encounter the following error: Response for preflight has invalid HTTP status code 401 ...

Directly transfer image to Cloudinary without creating a local file

I have integrated jdenticon to create user avatars upon signup in a node/express app. When working locally, I follow these steps: Create identicon using jdenticon Save the file on my local machine Upload the local file to cloudinary Here is a snippet o ...

An obstacle prevents the code injection process in the Chrome extension when a button is pressed

My basic chrome extension is not functioning correctly. More specifically, I am encountering an issue where the alert box does not appear when I click on the button in the popup. Here are the contents of my manifest.json file: {"manifest_version": 2, "n ...

JavaScript - Attempting to retrieve data using AJAX

Struggling with extracting data from an AJAX call using jQuery while implementing RequireJS for better maintainability and modularity in my JavaScript. Still new to RequireJS so not entirely sure if I'm on the right track. Just aiming to keep my JS mo ...

Encountering difficulties in accessing files displayed by serve-index in Express

My Node.js server using Express seems to be working fine for displaying directory contents, but I'm running into an issue when trying to access individual files. After clicking on a file listed in the directory, I keep getting an error message that sa ...

Tips on finding the key associated with a specific value

When a form is submitted, one of the fields being sent is an ID number instead of the name for easier processing by the server. For example: HTML dropdown select <select ng-model="myColor" class="form-control" ng-options = "color.ID as color.color ...

Adjusting the size of the Knob in Ionic 5 upon pressing it

Is there a way to change the size of the knob in an "ion-range" element when it is pressed? I have checked the documentation, but could not find any information in the "ion-range" section. I would like to make this adjustment in SCSS: Normal Behavior htt ...

What specific CSS code do I need to incorporate in order to style a chat application?

I'm currently working on styling a simple chat application, nothing too extravagant, but I'm encountering a few obstacles. My styling goals include: Aligning blue messages (from you) to the right and gray messages (from other users) to the left. ...

The callback function in jQuery does not function properly in a custom class or object

Hello, I am new to the world of programming so bear with me if this question seems basic. I am currently working on creating a simple wave effect to give the illusion of moving water. Initially, I achieved this using a straightforward jQuery function which ...

Enhance your user interface by incorporating badges into specific elements using Bootstrap version 5.2

I am currently using the most recent version of Bootstrap v5.2 and Vue 3 (for learning purposes). While searching on Stackoverflow, I came across a similar question, but it was related to an older Bootstrap version. In my project, I have a select element ...

Adding styles to specific child nodes within a p-tree component in PrimeNG

Starting off with a demonstration example: Check out this StackBlitz for primeng p-tree. I am utilizing primeng to construct a structure for polls and answers using p-tree. The hierarchy is as follows: Participants --> Polls --> Questions --& ...

Shifting hues with every upward and downward movement

I am experiencing a small issue with this JS code... -I have multiple divs that are changing automatically in rows as they move randomly... I want to change the color of the div moving up to green. And for the div moving down, I want to change the colo ...

Vue select component not refreshing the selected option when the v-model value is updated

Trying to incorporate a select element into a Vue custom component using the v-model pattern outlined in the documentation. The issue at hand is encountering an error message for the custom select component: [Vue warn]: Avoid directly mutating a prop as i ...

The jQuery request for the file was unsuccessful

Currently attempting to use jQuery.get('similar_products_stack.php'); as well as jQuery.get('./similar_products_stack.php'); My similar_products_stack.php file is designed to return an html array, however I keep receiving a 404 erro ...

replace the standard arrow key scrolling with a new custom event

Currently, I am in the process of creating a unique scroll box to address my specific needs. The standard html <select> box is not cutting it for me as I require two columns displayed, which I couldn't achieve with a regular <select>. Howe ...

Parsing text files with Highcharts

As a beginner in JavaScript and HighCharts, I am facing a simple problem that has me completely lost. My goal is to generate a scatter chart with three lines by reading data from a text file formatted like this: x y1 y2 y3 1.02 1.00 6.70 ...