0

Pardon the title, I have no idea how to describe this. I have a problem where my code changes variables it has no business changing, and I can't figure out why.

The code:

getCalendar (parameters, callback) {
    var returnData = this.calendars

    // If limit parameter is set, remove all but n events
    if (parameters.limit) {
      returnData.forEach((calendar) => {
        calendar.events = calendar.events.slice(0, parameters.limit)
      })
    }
    callback(returnData)
  }

this.calendars is filled with the data shown below. The code is supposed to return a copy of this.calendars, with the number of events limited by parameters.limit. This does work as intended, but this code also removes events from this.calendars somehow. So if I run the code with parameters.limit set to 3, and then again with parameters.limit set to 5, it will return 3 events both times.

This is a node app if it matters.

this.calendars

[
  {
    id: '5e29843erkjfassfv1h8@group.calendar.google.com',
    lastUpdate: '2019-09-18T10:16:32+02:00',
    summary: 'Calendar1',
    description: 'Description',
    timeZone: 'Europe/Oslo',
    updated: '2019-09-11T00:09:34.954Z',
    events: [ [Object] ]
  },
  {
    id: 'd3llqgg43irfkcf8pjfe8@group.calendar.google.com',
    lastUpdate: '2019-09-18T10:16:32+02:00',
    summary: 'Calendar 2',
    description: 'Description',
    timeZone: 'Europe/Oslo',
    updated: '2019-09-16T16:36:41.373Z',
    events: [
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object]
    ]
  }
]
Panda
  • 3
  • 1

1 Answers1

0

You are creating a shallow copy of this.calendars, so when you change returnData it mutates this.calendars also. Try this.

var returnData = JSON.parse(JSON.stringify(this.calendars))
Vaibhav Singh
  • 932
  • 7
  • 20