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

Bring in d3 along with d3-force-attract

Recently, I have installed D3 along with d3-force-attract. npm install @types/d3 -S npm install -S d3-force-attract I am currently facing an issue with importing d3 force attract as it is not recognized as a typescript module, unlike d3 itself. The inco ...

Subtracted TypeScript concept

Is it possible to create a modified type in Typescript for React components? import {Component, ComponentType} from 'react'; export function connect<S, A>(state: () => S, actions: A){ return function createConnected<P>(componen ...

Guide on merging non-modular JavaScript files into a single file with webpack

I am trying to bundle a non-modular JS file that uses jQuery and registers a method on $.fn. This JS must be placed behind jQuery after bundling. Here is an example of the structure of this JS file: (function($){ $.fn.splitPane = ... }(JQuery) If y ...

Ways to simulate a variable imported in the module being tested without it being a function parameter can be achieved by using describe.each and changing the mock value for each test

I have a requirement to test a function within my TypeScript module. module-to-test.ts import { config } from './app-config'; export const isSomethingWhatINeedSelector = createSelector( firstDependencySelector, secondDependencySelector ...

Exploring Angular Ag-Grid: Enhancing Row Expansion with a Simple Click

How can I increase the height of a particular row in Angular Ag Grid when clicked? I've edited the code in Stackbiz. Click here to see the edited data This is an example running from ag grid Tutorial Grid Tutorial Example ...

Encountering CORS Issue with Golang and Gin following a Redirect Situation

I am currently working on implementing Google OAuth2 in my Go web server using Gin. I have integrated two new endpoints - /google/sign-in and /google/callback. The former receives the request and redirects to the Google auth URL, while the latter is trigge ...

React's Material-UI ToggleButtonGroup offers a seamless way

I'm having trouble getting the ToggleButton selected property from material ui to function properly with ToggleButton. I followed the Material Ui documentation and created a StyledToggleButton as shown below: const StyledToggleButton = withStyles({ ...

Creating an enum in TypeScript can be accomplished by using the enum

What transformations do enums undergo during runtime in the TypeScript environment? Fruit.ts enum Fruit {APPLE, ORANGE}; main.ts let basket = [Fruit.APPLE, Fruit.ORANGE]; console.log(basket); The resulting main.js file remains identical to the .ts ver ...

How can I access a nested array in a JSON response using Swift?

Looking to access an array response within another array, successfully retrieved the friends array using this method let url = URL(string: "http://xyz/api/get-friends-in-meetings") AF.request(url!, method: .get, parameters: nil, encoding: JSONEn ...

Error Alert: Next.js TypeScript is reporting that the necessary packages are missing from your setup

As I work on developing a basic Next.js website using their TypeScript starter, everything was going smoothly with the 'yarn dev' command. However, out of nowhere, I started encountering an error message whenever I tried to run 'yarn dev&apo ...

Angular can display text on hover based on the state shown in a <td> element

Working on an Angular 7 project, I have a <td> element where I display different colors to indicate the status of a task: Red - Indicates 'Delayed' Orange - Indicates 'In progress' Grey - Indicates 'Rejected' Cu ...

What is the best way to retrieve the 5 most recent posts for each genre using Laravel's API

In the process of developing an application (which is my academic project), I am utilizing Laravel 5.4 as my API combined with Angular 5. The focus of my project revolves around a music blog, necessitating specific features like categories and subcategorie ...

Error: The object is not defined (evaluating '_$$_REQUIRE(_dependencyMap[32], "react-native-safe-area-context").SafeAreaView')

I am currently working on developing a chat application using react-native with the following dependencies: "dependencies": { "@react-native-async-storage/async-storage": "~1.17.3", "@react-native-community/masked ...

Pass along a JSON array from Express to Angular2

I have been working on sending a custom array filled with mongoose errors, and I am successfully creating the array. Below is the code snippet: student.save(function(err, student) { if(err) var errors = []; for (field in err.errors) { ...

agm-polygon fails to refresh with new points added

I've recently switched from using Google maps to AgmMaps and wanted to create a simple demo for drawing polygons on the map. Here's what I added to my project: You can find the stackblitz link with the code here <agm-polygon [strokeColor]="& ...

NodeJS unexpectedly exhibiting peculiar array functions

Within my NodeJS code, I have the following implementation: /* server.js */ 'use strict'; const http = require('http'), url = require('url'); METHODS = ['GET','POST','PUT','DELETE&a ...

Creating a nested list component using an array of objects

Seeking guidance for a coding task I recently completed. I was tasked with creating a multiple nested list from an array of objects. While I achieved the expected result, my code ended up being overly complicated and not very clean. I used a combination of ...

Encountering a Circular JSON stringify error on Nest.js without a useful stack trace

My application is being plagued by this critical error in production: /usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:137 ? `${this.colorize('Object:', logLevel)}\n${JSON.stringify(message, (key, value ...

What is the best way to retrieve a specific property from an array of objects in Angular 6 using typescript?

I am currently working on a budgeting application that incorporates an array of expenses with a price property. Each expense is defined within an Expense model in Typescript. While I can easily access the price property using ngFor loop in HTML, I'm c ...

Karma error `An unhandled exception occurred: Cannot locate module ‘karma’` is encountered during Jest Angular testing

Looking to implement Jest testing in my Angular project, I have followed all the setup instructions provided here. Here is an excerpt from my package.json: { "name": "jest-test", "version": "0.0.0", ... } Additionally, here ...