Problem encountered when attempting to add elements to an array within a nested

When running this code, everything works correctly except for the array pushing. After checking the console.log(notificationdata), I noticed that notification data gets its values updated correctly. However, when I check console.log(notifications), I see 7 identical entries with values matching the last one from notificationdata. There seems to be an issue with the way the data is being pushed into the array, and I'm struggling to figure it out. Any suggestions or ideas would be greatly appreciated.

var notifications = [];
reminder.days.value = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
reminder.times = [00:00]

      var uniqueNotificationData = {
        title: "It's time to take a dose",
        text: "Take " + medication + " for " + affliction + " now.",
        smallIcon: "../images/DosAvi_badge.png",
        icon: "../images/DosAvi_icon.png",
        every: "week",
        foreground: true
      }
      uniqueNotificationData.id = reminder.id;
      for(const day of reminder.days.value){
        for(const time of reminder.times){
          uniqueNotificationData.firstAt = getNextDayOfTheWeek(day, new Date(`Mon Jan 01 2020 ${time}`));
          //uniqueNotificationData.firstAt = new Date(`Wen Feb 26 2020 21:55`);
          console.log(uniqueNotificationData);
          notifications.push(uniqueNotificationData);
        }
      }
      console.log(notifications)

      cordova.plugins.notification.local.schedule(notifications);
    }

Answer №1

notificationdata represents an object, and within your loop, you're simply modifying one of its properties. By pushing the object to the array, you are actually adding a reference to it. Consequently, the resulting array consists of 7 references to the same object. To address this issue, you need to create a copy of the object first:

      for(const day of reminder.days.value){
        for(const time of reminder.times){
          const copiedNotificationData = {
              ...notificationdata,
              firstAt: getNextDayOfTheWeek(day, new Date(`Mon Jan 01 2020 ${time}`))
          }
          notifications.push(copiedNotificationData);
        }
      }

Answer №2

Due to the practice of reusing the same object, a new one isn't created.

The interesting thing about JavaScript object variables is that they merely contain a reference to an object. This means that whenever you modify the data in memory, you're actually updating the same information. Consequently, your array ends up with 7 references pointing to the exact same object.

To rectify this, it's necessary to generate a fresh object and insert it into the array:

for(const day of reminder.days.value){
    for(const time of reminder.times){
        const newNotificationdata = { ...notificationData };
        newNotificationdata.firstAt = getNextDayOfTheWeek(day, new Date(`Mon Jan 01 2020 ${time}`));
        notifications.push(newNotificationdata);
    }
}

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

What is the best way to monitor changes in objects within a JavaScript array?

Currently, I am in the process of developing a Todo application using electron and Vue.js. In my project, there is an array of objects called items. Each object follows this format: {id: <Number>, item: <String>, complete: <Boolean>, ...

Exploring the Dynamic Connection: AngularJS and MongoDB

As someone who is new to MEAN stack, I am currently working on creating a simple one-page application. My goal is to connect to MongoDB and retrieve values from a specific collection using a controller. During my search for an answer, I stumbled upon this ...

Tips for effectively utilizing the display: inline property in conjunction with ng-repeat

I am struggling to create a timeline with a broken structure on my website. I suspect that the issue lies in using display:inline. When attempting to apply this to my site: https://i.stack.imgur.com/4Ur7k.png the layout gets distorted: https://i.stack.i ...

Help Needed: Adding a Simple Element to jQuery Tabs Script

I recently came across a fantastic jQuery tabs script on a website called Tutorialzine. The link to the article can be found here. As I was implementing this script, I realized I needed to customize it by adding specific classes to certain tabs. Specifica ...

Include an additional value to the existing array

Here is the code snippet I am working with: $result = array(); $category_name = array(); foreach($category as $cat) { $category_name[] = $cat->category_name; // This value needs to be added to the result array $campaigns = $cat-> ...

Having trouble getting autocomplete to work with JQuery UI?

Currently facing issues in implementing the Amazon and Wikipedia Autocomplete API. It seems that a different autocomplete service needs to be used based on the search parameter. Unfortunately, neither of the services work when adding "?search=5" for Wikipe ...

Attempting to transfer user information to MongoDB using AngularJS and Node.js

Greetings everyone! I am currently working on a template and trying to develop a backend for it, starting with the registration form. Despite having some kind of connection between my mongodb and my app, data is not being sent to the database. Here is the ...

Any suggestions on resolving the "script timeout" issue while running a script using Python's SeleniumBase Library?

Recently starting to use Python, I am currently using Python's seleniumbase library to scrape a website and need to periodically run this fetch script. While experimenting, I encountered a script timeout error when the response time exceeded around 95 ...

The issue with displaying Fontawesome icons using @import in CSS-in-JS was not resolved

I recently changed how I was importing Fontawesome icons: src/App.css @import "@fortawesome/fontawesome-free/css/all.css";` After shifting the @import to CSS-in-Js using emotion: src/App.js // JS: const imports = css` @import "@fortawes ...

Troubleshooting Error 405 in AJAX, Javascript, Node.js (including Body-Parser and CORS), and XMLHttpRequest

I have been working on creating a JSON file from buttons. While I am able to retrieve data from the JSON files that I created, I am facing issues with posting to them using XMLHttpRequest and Ajax. Interestingly, I can add to a JSON file using routes just ...

Oops! An error occurred: fs.readFileSync is not a valid function to perform the Basic

I'm facing a dilemma - I have a relatively simple app (I'm still new to Node): App.js import * as RNFS from 'react-native-fs'; var config_full; // readFile(filepath: string, encoding?: string) RNFS.readFile('./config.toml', ...

Ways to adjust the height of one panel based on the height of surrounding panels

I have a layout with three panels: two on the left side and one on the right. <div class="row"> <div class="col s6"> <div class="panel"> content1 </div> <div class="panel"> ...

Looking to streamline a JavaScript function, while also incorporating jQuery techniques

I've got this lengthy function for uploading photos using hidden iFrames, and while it does the job well, it's quite messy. I'm looking to simplify it into a cleaner function with fewer lines of code for easier maintenance. function simplif ...

Tips for retrieving multiple values or an array from an AJAX request?

Is there a correct way to pass multiple sets (strings) of data back after executing an ajax call in php? I understand that echo is typically used to send a single string of data back, but what if I need to send multiple strings? And how should I handle th ...

Is it advisable to use an autosubmit form for processing online payments?

Situation: In the process of upgrading an outdated PHP 4 website, I am tasked with implementing an online payment system. This will involve utilizing an external payment platform/gateway to handle transactions. After a customer has completed their order ...

jsonAn error occurred while attempting to access the Spotify API, which resulted

Currently, I am working on acquiring an access Token through the Client Credentials Flow in the Spotify API. Below is the code snippet that I have been using: let oAuthOptions = { url: 'https://accounts.spotify.com/api/token', method: ' ...

The websocket server implemented in Node.js with the use of the "ws" library is exhibiting a peculiar behavior where it disconnects clients at random intervals,

My WebSocket server implementation is quite simple: const WebSocket = require('ws'); const wss = new WebSocket.Server( { server: server, path: "/ws" }); wss.on('connection', function connection(ws, req) { console.log("Connect ...

Using Angular JS for Traditional Multi-page Websites

Lately, I've been diving into Angular 2 and I have to admit, it's an impressive framework for building single-page applications. But here's the thing - how would one go about integrating Angular with a traditional website (maybe using codei ...

Encountering issues with the routing in my live Node.js project: ERROR

I am encountering issues with my project in production. I suspect it could be due to a misconfiguration or something similar. Could you please review the provided code snippets and see if you notice any potential issues? The project works fine locally, bu ...

An element in CSS that has a position of fixed and a width of 100% surpasses the dimensions of its

My element has the CSS properties position:fixed and width:100%, causing it to be larger than its parent elements. Despite the complexity of my code, I have attempted to simplify it for better understanding. Below, you can see that the green box exceeds ...