What is the best way to access an element from an array nested within an object in Firestore?

In my Firestore database, the structure includes multiple arrays within the "reserved items" object. Each array contains more than one element. How can I extract the "returnDate" element from every single array within the object?

Answer №1

reserved_items is a field with type Array, where each element is a map or JavaScript Object. To access the elements of this Array, you will need to iterate over it using the dot notation concept. Below is an example utilizing the dot notation along with the forEach() method:

  var documentReference = db.collection('...').doc('63ufq....');

  documentReference
    .get()
    .then((document) => {
      if (document.exists) {
        const reserved_items = document.get('reserved_items');

        reserved_items.forEach(item => console.log(item.returnDate));

      } else {
        // Undefined document data
        console.log('Document does not exist!');
      }
    })
    .catch((error) => {
      console.log('Error retrieving document:', error);
    });

Answer №2

To begin, retrieve your file from your firestore database.

var docRef = db.collection("cities").doc("SF");

docRef.get().then((doc) => {
    if (doc.exists) {
        console.log("Document content:", doc.data());
    } else {
        // doc.data() will be undefined in this scenario
        console.log("Document not found!");
    }
}).catch((error) => {
    console.log("Error retrieving document:", error);
});

At this point, you will find your data inside doc.data(), with 'reserved_items' as one of its properties. You can then utilize the map() function to loop through 'reserved_items' and save the required information in a variable.

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

Conceal navigation buttons on the first and last pages of the slider

I'm attempting to develop a slider that hides the "previous" button when it is on the first slide and hides the "next" button when it reaches the last slide. The slider will be created using a combination of PHP, forms, and JavaScript. Below is the H ...

Retrieve the identification of elements with dynamically generated ids

I've dynamically generated a set of elements using Handlebars, as shown below {{#floor as |room i|}} <div class="btn-group-toggle" data-toggle="buttons" > <label class="btn btn-secon ...

Is there a way to extract the properties of a CSS class from a stylesheet and convert them into a hash using JavaScript or jQuery?

I am exploring a way to extract key value pairs from a CSS stylesheet related to a specific class or id into a JavaScript object for data accessibility. It is important to mention that I do not intend to apply this class directly to any DOM elements. In ...

Utilizing a V-for/V-if loop to iterate through a multi-dimensional array and filter data based on date

I'm facing a challenge with setting up a v-for loop for an array I've constructed, which is already in the desired format Below is a snippet representing the data format. Essentially, I want to create a table for employees where the header consi ...

How can one go about constructing abstract models using Prisma ORM?

Among my various prisma models, there are common fields such as audit fields like created_at and updated_at. model User { id Int @id @default(autoincrement()) created_at DateTime @default(now()) updated_at DateTime @updatedAt email ...

Encountering error while processing order in React.js using Stripe

const processPayment = async () => { try { const paymentResponse = await stripe.confirmCardPayment(clientSecret, { payment_method: { card: elements.getElement(CardElement) } }); ...

Deciphering the creation process behind the "WhatsApp Web" front-end page

I'm currently exploring the creation process of the front-end page for WhatsApp Web, specifically focusing on the list of contacts located on the left side (<div id="pane-side">). The contact names within this list are identified by the class "e ...

Strange error message: Attempting to set properties of null (changing 'innerHTML')

I have been working on a project where I am creating a website that retrieves data from a specified URL, displays it on the front end, and performs certain functionalities with that data (although this part is not yet implemented). However, I have encounte ...

adjusting three sections within a flexible navigation bar

Having difficulties creating a dynamic navbar that changes on scroll and keeping the elements within the nav fixed when the menu options appear. For reference, you can check out this codepen: http://codepen.io/timothyfernandez/pen/azXQPV Any assistance w ...

The process of setting up React in the terminal becomes tricky when the VS code editor is directing to a non-existent path

Issue with VS Code editor not recognizing existing path Recently attempted to install React using the npx command in the terminal, following steps from various tutorials on YouTube. Despite trying all suggested methods, the installation didn't succee ...

What's causing the unexpected rendering outcome in Three.js?

Here is a mesh created in Blender: https://i.sstatic.net/KBGM5.jpg Upon loading it into Three.js, I am seeing this result: https://i.sstatic.net/PCNQ8.jpg I have exported it to .obj format and ensured all faces are triangulated. I am not sure why this is ...

Making the Select Tag function as an on-click event in JQuery

So I currently have a tab set up that functions as on click links when viewed on desktop. However, for tablet and mobile devices, I need it to be transformed into a select drop down list while maintaining the same functionality. Below is the code used for ...

Showing no background color until the user lifts their finger

I am currently in the process of developing a website. The navigation on the website starts off as transparent (background: transparent) when opened, but as soon as you start scrolling, it should transition to a colorful state with shades like grey, midnig ...

How can you resize an HTML table by dynamically adding or removing rows and columns?

Is there a way to dynamically add or remove rows and columns from an HTML table, also known as resizing it? The table should have a rectangular shape as it will later represent a 2D array value. Since the table will be refreshed frequently and may become ...

Creating toggling elements in Vue.js using dynamic v-show based on index and leveraging falsey v-if

What is the most effective way to use v-show for toggling elements based on their index? I have been able to toggle the elements, but when you click on the element that is already open, it does not close. <div v-for="(btn, index) in dataArray"> ...

The issue persists with the addEventListener function not working multiple times

My issue is that the addEventListener function is only working for the 'scroll' event and not for 'addMoreFields' or 'removeFields'. If I move the scroll section down, then it works for 'addMoreFields' and 'remo ...

uWebSockets supporting multiple concurrent user sessions

To keep things simple, let's assume that my server is running just one uWebSockets instance: struct UserData { uWS::WebSocket<true, uWS::SERVER> *ws; bool logged_in = false; ID user_id; }; uWS::SSLApp() .ws<UserData>( ...

Dealing with Angular.js $http intercept error "net::ERR_CONNECTION_REFUSED"

Currently, I am attempting to create a universal error handler for my website utilizing $http interceptors. However, it seems that the interceptors are not functioning as intended. I have set up interceptors for 'response' and 'responseErro ...

Is it possible for a form to direct submissions to various pages depending on the value of certain fields

I need to set up a text field and submit button that will redirect users based on their input: index.html: If the user inputs "123" in the text box and clicks submit, they should be redirected to john.html page. AND If the user inputs "456" and clicks s ...

I am having trouble establishing a connection to the JavaScript MQTT server

Error Encountered: WebSocket Error 12031 - The Server Connection Was Reset In order to subscribe to MQTT messages from the user interface, the code below is being utilized. A Mosquitto broker is currently running on my local machine, with the IP address s ...