0

I dont understand why JS is doing like this. I have declared a class calendar which has an js object as property this.calendar

class SweetCalendar{
    constructor(){
        this.i_weeknumber =  46;
        this.getCalendar();
        this.filterCalender();
    }
    filterCalender(){
        var a = this.calendar
        for(var i in a){
            for(var j in a[i]){
                if(a[i][j]["Weeknumber"] != String(this.i_weeknumber)){
                    delete a[i][j];
                }
            }
        this.calendar_week
        }

With the function filterCalendar i want to create a new object which is a subset of the this.calendar property. The function works as designed but this.calendar has now the same values like this.calendar_week. I dont understand why js is doing like this. I copied the object to the variable a so why is this.calender edited by the function filterCalendar?

aejsi5
  • 147
  • 8
  • 1
    Can you add all of your code? I'm confused by the origins of some of your data. Is `this.calendar` initialized as a value somewhere? It would be `undefined` from what you've shown – Andrew Nov 08 '20 at 18:02
  • 1
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+object+copy+property+changes) of [Modifying a copy of a JavaScript object is causing the original object to change](https://stackoverflow.com/q/29050004/4642212). – Sebastian Simon Nov 08 '20 at 18:02

2 Answers2

1

When assigning var a = this.calendar means that you copy the object by reverence.

Check 4 ways to clone objects in JavaScript.

strdr4605
  • 3,796
  • 2
  • 16
  • 26
0

Because you never created a new object, all you did was created another reference variable which is pointing towards the same object as 'this.calender'. Consider the example below:

    var a={name:"john"};
    var b=a;
    b.name="doe";
    console.log(a.name)  //this will print doe as both a and b are pointing to the same object

You need to clone the object in order to get the functionality that you are trying to achieve.

Naveen Chahar
  • 561
  • 3
  • 10