Transform Firestore JSON data into a TypeScript array

Extracting and formatting data from Firebase for visualization purposes can be challenging after successfully working with it in HTML. I am currently dealing with a FirebaseListObservable that contains three value-types, but only one of them needs to be included in the array for visualization. How can I effectively convert a FirebaseListObservable to an array using TypeScript?

I need to convert the data in order to create graphs within my app.

Here is the TypeScript code for retrieving the data:

this.measure = this.db.list('/Users/' + this.username + '/Measure');
enter code here

And here is the TypeScript code for implementing chartjs:

this.data = [12, 24, 91, 23] 

The goal is to populate 'this.data' array with the actual data retrieved from Firebase.

Answer №1

To start, create an empty array called data=[];

Next, retrieve the data using .subscribe()

this.db.list('/Users/'+this.username+'/Measure').subscribe(measures => {
    measures.forEach(measure => {
      this.data.push(measure.number);//.number refers to your specific field in firebase
    })
  })

This code will fetch all the lists, iterate through each item, and add the desired values to the array.

Answer №2

The FirebaseListObservable represents an observable object. This means that upon subscribing to it, you will receive the actual list itself, which in this case is the array containing the desired data.

this.measurementData: FirebaseListObservable<Measure[]> = this.db.list('/Users/'+this.username+'/Measure');
this.measurementData
    .map(data => data.numbers) // extract only the numbers field to get an array of arrays
    .map(numberArrays => numberArrays.reduce((current, previous) => current.concat(previous))) // concatenate all arrays into a single one
    .subscribe(numbersArray: number[] => {
        console.log(numbersArray);
    });

interface Measure {
    date: Date;
    location: string;
    numbers: number[];
}

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

Converting a multidimensional array into a JSON array using PHP: A step-by-step guide

I have an input array in PHP that I've been trying to convert into a JSON object array. Despite attempting some predefined functions, I haven't been successful because I'm still new to this. [educationTitle] => Array ( [0] =&g ...

The value of an Angular rxjs BehaviorSubject can be updated using the value property directly, without calling

While testing my code, I stumbled upon unexpected mutation. Perhaps I am doing something wrong. User constructor( public id: number, public education: Education[] ){} UserStateService private user = a new BehaviorSubject<User>(null); setUser(us ...

Getting information in JSON format

Within my controller class, I have the following method: import javax.json.Json; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.c ...

Typescript type for selecting only string[] keys in an object

I am looking for a specific type: interface Filter<P extends object> { label: string; options: FilterOption[]; key: StringArrayKeyOf<P>; } The definition of StringArrayKeyOf is as follows: type StringArrayKeyOf<T extends object> = ...

Error message in MongoDB Compass: JSON input terminated unexpectedly

I recently exported my MongoDB Collections locally as JSON files on my personal computer. Now, I am attempting to import these Collections onto my root server using MongoDB Compass. However, every time I try to export the Collection, I encounter the follow ...

Having trouble accessing JSON values in FullCalendar with Struts2

On my JSP page, I have iterated buttons where I have two buttons on iteration <s:iterator value="%{#session.allrefrence}"> <button class="btn " style=" background: #DB7093;color: white; " id="ref" value="%{refrenceid}" ></button> ...

Verifying email availability using VB.NET WebMethod, JSON, and CustomValidator

I have been researching this issue extensively, both on this site and others, but have yet to find a solution that works for me. My goal is to validate whether a given email address is already in use in a database during the registration process. On my Re ...

PHP: Conversion of data types and modifying elements within a foreach loop

Today, I encountered a peculiar scenario. While trying to change an array element within a foreach loop, I was aware that it can be achieved using references. foreach((array)$output['subjectComposite'] as &$subjectComposite){ $subjectC ...

Exploring the usage of intervalTimer with async and fakeAsync functions

In a particular section of the Angular Testing Guide, it discusses how to test components with asynchronous services, pointing out that: When writing test functions involving done rather than async and fakeAsync, it may be more cumbersome but remains a ...

What is the best way to structure JSON data in JavaScript in order to effectively utilize a service?

I am attempting to connect to a service and have confirmed the correct connection, but I am encountering an error. I suspect that the JSON format may be incorrect. ERROR: net::ERR_ABORTED 500 (Internal Server Error). The technology being used is Jquery A ...

Issue with Jest mock function failing to trigger axios instance function causing it to return undefined

I initially found a solution on this StackOverflow thread However, I wanted to add my own helper function that generates a fresh Axios instance with the user's authentication token. Here is what I came up with: import axios from "axios"; c ...

Nested mapping of objects in a mapped object

I'm attempting to iterate through an array within another array that has already been iterated My objective is to display the userName and products each user has. To achieve this, I first map the main data array to show the userName of each object. ...

Dynamically removing buttons with JQuery

I am trying to dynamically add buttons to a page based on an array, but I'm running into a problem. Whenever I add a new name to the array, it prints out all of the buttons instead of just the one I added. I need help figuring out how to erase all the ...

Encountering Typescript issues while trying to access @angular/core packages

Recently, I made an update to my Ionic app from Angular 7 to Angular 8, and an odd error popped up: The issue lies in the fact that I am unable to access any of the standard classes stored in the @angular/core module. This same problem is occurring with o ...

React with Typescript - cannot be expressed as a function

I am currently exploring ReactJS and Typescript. While trying to authenticate a user using the methods below, I encountered the following error message: Unhandled Rejection (TypeError): auth.authenticate is not a function onSubmit src/components/Login/ind ...

I am interested in creating a checkbox filtering system using Angular

Below is the display from my project's output window view image description here In the image, you can see checkboxes on the left and cards on the right. I want that when a checkbox is checked, only the corresponding data should be shown while the r ...

Generating JSON data with Express.js and MySQL

I have successfully connected to a mysql database. However, I am facing an issue where I cannot seem to get the query data to output in the console, regardless of whether there is an error or not. Could there be something wrong with how I've configure ...

I am encountering challenges with submitting the form

I am encountering an issue where I want to submit the form on button click and navigate to the next page, but instead I get an error message saying: "Form submission canceled because the form is not connected". Does anyone have a solution for this problem ...

What is the significance of requiring a specific string in a Typescript Record when it is combined with a primitive type in a union?

I am facing an issue with the following data type: type ErrorMessages = Record<number | 'default', string>; When I declare a variable like const text: ErrorMessages = {403: 'forbidden'}, Typescript points out that default is miss ...

Creating an index for a JSONB column in Postgres that contains an array of JSON values

In my postgres database, I have a table named "employee" with a JSON column called "mobile". This column stores an array of JSON values representing employee mobile numbers. e_id(integer) name(char) mobile(jsonb) 1 John [{\"mo ...