Storing an array of objects in Firestore using JavaScript presents a challenge

I am attempting to save an object to Firestore which includes an array:

{
  returnMode: false,
  id: "SE-74c5219a-acfe-4185-9e33-f78b10ac3f1e",
  prices: [
    {
      price: {
        twoHours: 0,
        firstHour: 0,
        id: "zero",
        unlock: 0,
        final: 0,
      },
      permission: { id: "GENERAL" },
    },
    {
      price: {
        twoHours: 150,
        unlock: 100,
        id: "oebb_low",
        firstHour: 50,
        final: 50,
      },
      permission: { id: "OEBB" },
    },
  ],
}

When I hard-code this object into the Cloud Function, it successfully saves to Firestore without any issues. However, if I replace the array in the object with a variable like this, it continues to work:

const array = [
    {
      price: {
        twoHours: 0,
        firstHour: 0,
        id: "zero",
        unlock: 0,
        final: 0,
      },
      permission: { id: "GENERAL" },
    },
    {
      price: {
        twoHours: 150,
        unlock: 100,
        id: "oebb_low",
        firstHour: 50,
        final: 50,
      },
      permission: { id: "OEBB" },
    },
  ];
{
  returnMode: false,
  id: "SE-74c5219a-acfe-4185-9e33-f78b10ac3f1e",
  prices: array,
}

However, when the array is dynamically generated by my program rather than hard-coded, it fails to save. The following code snippet shows how the array is created:

const bikeBoxPriceArray = [];

for (let i = 0; i < bikeBoxPermissionArray.length; i += 1) {
  const doc = bikeBoxPermissionArray[i];
  
  const bikeBoxPriceArrayElement = {
    permission: {
      id: doc.id,
      name: doc.name,
    },
    price: {
      id: priceId,
      unlock: priceUnlock,
      firstHour: priceFirstHour,
      twoHours: priceTwoHours,
      final: priceFinal,
    },
  };

  bikeBoxPriceArray.push(bikeBoxPriceArrayElement);
}

I have confirmed using

bikeBoxPriceArray instanceof Array
that it is indeed an array. What could be causing this issue? I have tried various solutions but cannot seem to identify the problem. Why does it work when hard-coded but not with a variable?

This code is executed within a Firebase Transaction and no error message is displayed, just the location of the error.

Answer №1

After some research, I came across a solution to my own question in this helpful post.

To successfully merge the object with the array, it is important to stringify the array first and then parse it again as shown below:

const array = JSON.parse(JSON.stringify(bikeBoxPriceArray));

const sessionDocObj = {
  returnMode: false,
  timestamp: {
    // sessionCreated: admin.firestore.FieldValue.serverTimestamp(),
    sessionCreated: "Karoline",
  },
  id: "SE-" + uuidv4(),
  prices: array,
};

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

Pass JavaScript variables to a PHP file with the help of AJAX

Hey there, I'm new to developing web-based applications and currently learning about AJAX. I've run into a problem while trying to make an AJAX request with user inputs as variables and fetching the same variables in a PHP file. Below is the code ...

Using jQuery, you can easily apply a new class to a div when it is

I'm currently facing an issue with adding a class of "active" to a div upon clicking it using jQuery. My goal is to apply the css class of active in order to give the button a distinct color (or the hover effect.) Unfortunately, I have been unsuccess ...

Tips for transferring a value from a view to a controller using AngularJS

I've created a controller that dynamically generates tables based on data retrieved from the backend using $http.get. I'm wondering how I can pass a value to this controller from the view, indicating which URL it should use to fetch the data for ...

Creating an overlay with CSS hover on a separate element and the ::before pseudo class

Issue: I am struggling to display the overlay when hovering over the circle element, rather than just the image itself. I have attempted to achieve this using CSS, but can't seem to make it work as intended. Any guidance and examples using JavaScript ...

Connect the input field to the grid component

How can I sync the value of the SearchFilter with the FilterGrid to effectively filter the data (refer to code below)? I'm facing an issue where the field clears out the value as I type. There seems to be a problem in how I'm utilizing the state ...

Is it possible to trigger a reflow prior to initiating a lengthy JavaScript operation?

Ready to face the criticism, I understand that this question has been asked many times before, and I am aware that there are likely more efficient ways to achieve what I'm trying to do... In a JavaScript function, I have a process that can take up to ...

The dropdown on my website is malfunctioning

There seems to be an issue with my dropdown button. Previously, it only appeared when clicking on a specific part of the button. I attempted to resolve this problem but unfortunately, the dropdown no longer works at all and I am unable to revert my changes ...

performing a jQuery AJAX call from a UIWebView during the initial launch of the app following installation

We have a uiWebview that uses jquery for an ajax request to log in. It functions flawlessly on mobile safari and all browsers. However, when the application is launched for the first time after installation, the ajax request seems to be sent out but no re ...

Guide to generating a map of a Java POJO class or JSON String with basic data types

I need to create a Map (String, Object) with the following format: {AssessmentId=0, Physical_name='ram', Physical_height=20, Physical_weight=60} This map will be constructed from my Pojo Class - InitialAssessment public class InitialAssessment ...

Utilize Grunt to retrieve a JSON object from a file

I'm interested in utilizing the grunt-hash plugin to rename my JavaScript files. This plugin generates a new file that contains a map of renamed files: hash: { options: { mapping: 'examples/assets.json', //mapping file so your s ...

Updates to class variable values in jQuery are failing to take effect

Attempting to create my first JavaScript class has presented some challenges, specifically when it comes to updating a class variable. Despite hours of testing different approaches, I still can't seem to get it right! function ClassName(productId) { ...

Running a cfquery in a cfc and passing parameters through AJAX

I am currently setting up a system to retrieve data from my ColdFusion database using JavaScript. However, I am encountering an error and unsure of its cause since I am relatively new to CF. The specific engine I am utilizing is ColdFusion MX 7. Below is ...

The data contract for type 'Newtonsoft.Json.Linq.JToken' is a recursive collection that is not supported. Please consider adjusting the collection definition

I am encountering an issue while trying to iterate through the server's response. The error message I keep receiving is: The data contract 'Type 'Newtonsoft.Json.Linq.JToken'' is a recursive collection, which is not supported. To ...

Looking to Share Your Words on Tumblr?

When it comes to interacting with Tumblr, I have no issues using the GET method. However, as soon as I attempt to use the POST method for my Tumblr blog, an error is thrown: ({"meta":{"status":401,"msg":"Not Authorized"},"response":[]}); Below is the cod ...

Stripping out only the position attribute using jQuery

I have implemented a code with the following characteristics: The navigation items' texts are hidden behind certain Divs, which I refer to as Navigation Divs. When the mouse hovers over these pixels (navigation Divs), the text that is behind the ...

Can Firebase data be updated in real-time in a Vue app?

Utilizing Firebase for Authentication and integrating a database into a Vue app, my current task involves monitoring changes within a 'friends' collection specific to a user. The objective is to seamlessly display the list of friends while refle ...

What is the best way to create a button with this functionality?

In the form that I have created, it is opened in a bootstrap modal style. This form contains a button that, when clicked, triggers an alert box to appear. The code snippet used for this functionality is as follows: echo "<script>"; echo "alert(&apos ...

Karma testing shows quick results, but in reality, the performance is sluggish

If you'd like a visual explanation, check out this video (or see the gif below): The Karma progress reporter may indicate that the tests are taking milliseconds, but in reality, it's taking much longer... I mentioned this on Twitter and was adv ...

The FireBase getToken function with the forceRefresh set to true has failed to perform as expected

I encountered a problem with this code snippet from Firebase when trying to run it in Angular 2 CLI. It gives an error of 'unreachable code'. How can I fix this issue and get it to work properly? firebase.auth().currentUser.getToken(/forceRefres ...

Issues with basic emit and listener in socket.io

I recently inherited an App that already has socket IO functioning for various events. The App is a game where pieces are moved on a board and moves are recorded using notation. My task is to work on the notation feature. However, I am facing issues while ...