Tips on avoiding updates to a defined object when a new object is filtered (created from the original object)

Is there a way to filter an array of objects based on their year without altering the original object? Whenever I apply a filter, it affects both the newly created object and the original one. However, I need the original object to remain unchanged so that I can apply different filters.

I've experimented with methods like .assign, JSON.parse(JSON.stringify(Object)), and the clone deep function but haven't found a solution yet.

This is the component code:

export class LeaderboardComponent implements OnInit {
  title = "Leaderboard";
  public navList = [];
  public navFilterList = [];
  routeCount = 0; 
  logsCount = 0;
  completeJourneys = 0;
  selectFilter = "";
  selectDateFilter = "";
  currentDate = new Date;
  minutes = 1000 * 60;
  hours = this.minutes * 60;
  days = this.hours * 24;
  month = this.days * 30;
  years = this.days * 365;
  currTimestamp = this.currentDate.getTime();
  clonedObject;
  objCopy = [];

  constructor(private leaderboardService: LeaderboardService) { }

  ngOnInit() {
    this.leaderboardService.getNavList()
    .subscribe(data => {
      this.navList = data;
       this.objCopy = Object.assign([], data);
      console.log("here");
      console.log(this.objCopy);
    });
  }


  orderByDate(){
    console.log(this.objCopy);
    var tempLogArray = 0;
    this.navFilterList = this.objCopy;

    if(this.selectDateFilter != "all"){

      for(var i = 0; i < this.navFilterList.length; i ++){
        for(var j = 0; j < this.navFilterList[i].user.routes.length; j ++){
          for(var k = 0; k < this.navFilterList[i].user.routes[j].logs.length; k++){
                var logDate = new Date(this.navFilterList[i].user.routes[j].logs[k].attemptDate);
                this.navFilterList[i].user.routes[j].logs[k].timestamp = logDate.getTime(); 
          }
          this.navFilterList[i].user.routes[j].logs =  this.navFilterList[i].user.routes[j].logs.filter(log => ((this.currTimestamp - log.timestamp)/this.years)  < 1);
        }
      }
      console.log("here year");
    }
}
}

The HTML code calling the filter by date function:

              <select [(ngModel)]="selectDateFilter"  (change)="orderByDate()" class="form-group" style="width: 100px;" >
                <option  disabled selected value="" >Order by: </option>
                  <option  value = "week">Last 7 Days</option>
                  <option  value = "month">Last Month</option>
                  <option  value = "year" >Last Year</option>
                  <option  value = "all" >All Time</option>
                </select>

I expect objCopy to always retain the data fetched from the JSON file via API, but instead, it gets updated with the filtered data.

Answer №1

When variables are assigned a non-primitive value, they are provided with a reference to that specific value. This reference directs them to the memory location of the object. In essence, the variables do not actually store the value themselves.

For a more effective solution, consider utilizing the spread operator:

this.navFilterList = [...this.objCopy];

UPDATE:

I have observed that you are making modifications to the object, rendering the spread operator and slice ineffective as they only create shallow copies, not deep clones.

To achieve a deep clone, revert back to your original method of using

JSON.parse(JSON.stringify(Object))
:

this.navFilterList = JSON.parse(JSON.stringify(this.objCopy));

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

typescript function intersection types

Encountering challenges with TypeScript, I came across the following simple example: type g = 1 & 2 // never type h = ((x: 1) => 0) & ((x: 2) => 0) // why h not never type i = ((x: 1 & 2) => 0)// why x not never The puzzling part is w ...

What is the best way to combine two arrays along with their keys and values in CodeIgniter, then seamlessly insert the result into a

I have a manually created array and a posted array. My goal is to combine the keys with their corresponding values. Below are my arrays. I am looking to achieve something like [1st_service] => 11, [2nd_service] => 12, etc., and then insert this into ...

Encountering a CORS problem when an Angular application communicates with a .NET Core API integrated with the Sustainsys.Saml2 library and Azure Active Directory serving as the Identity

Our team is currently working on implementing SAML authentication in a .NET Core API to handle requests coming from an Angular application. We are utilizing the package Sustainsys.Saml2.AspNetCore2 (version 2.9.2) for .NET 6, and we have successfully set u ...

Mastering the integration of NestJS with Redis for microservices

Currently, I am diving into the world of nestjs microservices. I am curious, what commands are available for me to use? const pattern = { cmd: 'get' }; this.client.send<any>(pattern, data) Additionally, how do I go about retrieving data ...

Angular2 - Showing parameters in modal interface

I am working on an Angular5 app and have a component.html file with a function called markerClick that opens a modal. However, I am facing challenges in displaying the item.lat parameter in the modal and would appreciate your assistance. Below is the code ...

Guide on integrating a personalized theme into your Ionic 5 app

I'm looking to customize the theme of my Ionic 5 app by adding a red-theme to variables.scss @media (prefers-color-scheme: red) { :root { --ion-color-primary: red; Afterwards, I attempted to initialize it in index.html <meta name=" ...

Utilizing absolute path in Typescript: A comprehensive guide

I am currently working on a project written in Typescript running on NodeJS. Within the project, I have been using relative paths to import modules, but as the project grows, this approach is becoming messy. Therefore, I am looking to convert these relativ ...

Having an issue with my code in angular 12 where I am unable to successfully call an API to retrieve a token, and then pass that token to another API for further processing

Here is the code snippet containing two methods: getToken and validateuser. I am fetching the token from getToken and passing it as a parameter to validateuser. However, before retrieving the token, my second API call is being executed. ...

Translate Firestore value updates into a TypeScript object

Here are the interfaces I'm working with: interface Item { data: string } interface Test { item: Item url: string } In Firestore, my data is stored in the following format: Collection Tests id: { item: { data: " ...

Embedding Globalize.js into an Angular component

Hey there! I'm currently working on building an Angular 4 application that needs to support L10n. I've decided to incorporate globalize into my project. Below is a snippet of my App component: import { Component, OnInit } from '@angular/c ...

Adding a unique object to a different user class with cloud code on Parse.com

I need to incorporate the current user object ID array into a user's "followers" column in Parse, but because of security restrictions, I have to use cloud code. Unfortunately, I don't know much about JavaScript and could use some assistance. Her ...

Utilizing Angular 8's Reactive Form to Transform Checkbox Event Output into a String Format

My form is reactive and includes a field called Status, which can have the values 'A' or 'I': this.form = this.formBuilder.group({ result_info: this.formBuilder.array([ this.getResultcontrols()]), stat ...

Utilizing a Typescript class interface does not maintain the original method types

Struggling to define a Typescript interface and implement it in a class. The issue lies in the method signatures of the interface not being applied to the class as expected. Below is a simplified example: export interface Foo { bar(value: string): voi ...

How to translate a list of integers into JSON format using Java

Can someone help me with converting an array of integers into JSON format? The array is created in Java and I need it in the form of a JSONArray or JSONObject. Here's my code: int[] tableau = new int[6]; JSONArray jsonArray = new JSONArray(); int k ...

Tips for implementing daterangepicker js in an Angular 2 project

I'm currently working on an Angular 2 project and I'm looking to integrate the daterangepicker.js library for a date range picker. If you're not familiar with it, you can find more information about the library here. Here's the HTML co ...

Refine objects based on their properties without removing them from the dataset

I have a specific object structured as follows: var myObj: { 2:"None", 20:"A", 31:"A", 32:"A", Social:"B", Method:"None" } My goal is to retrieve the object without the properties 'Social' and 'Method'. Initia ...

Summarize the array of objects and find the average value for each distinct object name

I'm facing a challenge with an array structure: const originalArray = [ { name: "a", value: 1 }, { name: "a", value: 2 }, { name: "a", value: 3 }, { name: "b", ...

Ran into an issue while executing ng build --prod: The JavaScript heap has run out of memory

After executing ng build --prod, I encounter the error below. What steps can I take to resolve this issue? FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory ...

The error message displayed by Create React App states: "You cannot utilize JSX without the '--jsx' flag."

I need help with overcoming this particular issue in a TypeScript based React application: Encountering an error stating "Cannot use JSX unless the '--jsx' flag is provided" ...

Having trouble retrieving data from an array within a JSON object

I've spent countless hours searching for a solution to this issue, but no matter what I attempt, I keep running into the same error message. The dreaded error I keep encountering is: Fatal error: Cannot use object of type stdClass as array My curren ...