Putting retrieved data from firebase into an array using Angular and Firebase format

Hey everyone, I'm currently facing an issue with formatting my Firebase data into an array.

Below is the service where I am retrieving data from Firebase:

File name: subcategory.service.ts

export class SubcategoryService {

  subcategoryRef: AngularFireList<any> = null;

  constructor(private db: AngularFireDatabase) {
   this.subcategoryRef = db.list("/subCategory");
  }

  getSubCategoriesById(inp_subCatid: string): Observable<any[]> {
    return this.subcategoryRef.snapshotChanges().pipe(
      take(1),
      map(changes => changes.map(c =>
        ({ key: c.payload.key, ...c.payload.val() })
      ).filter((subCat) =>
        subCat.catid === inp_subCatid
      )
    ));
  }
}

I am calling the function getSubCategoriesById() in the following file:

File name: subcategory.page.ts

this.SubcategoryService.getSubCategoriesById("cat01")
      .subscribe(subCategories =>
        this.subCat = Object.values(subCategories)
    )

The structure of the object that I am retrieving appears as shown in https://i.sstatic.net/GYGA9.png. There is an array containing one object which holds my desired objects.

However, my goal is to format the data into the following structure:

[
 alcoholic:{
             active:true,
             ageRating: true,
             category: "cat01"
             ...
            },
 warmdrinks:{
             active:true,
             ageRating: false,
             category: "cat01"
             ...
            },
 softdrinks:{
             active:true,
             ageRating: false,
             category: "cat01"
             ...
            },
]

This way, I will have an array with three objects inside it.

My Firebase database for this case is structured as shown in https://i.sstatic.net/HdCGu.png.

If anyone can provide assistance or requires more information, please let me know. Thank you!

Answer №1

In my opinion, it would be beneficial to utilize valueChanges instead of snapshotChanges()

transform your approach from using this.getSubCategoriesList().snapshotChanges().pipe(

to

using this.getSubCategoriesList().valueChanges().pipe(

By using valueChanges, you will receive an Observable containing only the raw document data without any additional metadata.

This recommendation is based on the assumption that you are working with Angularfire...

Answer №2

To customize the attributes you extract from an array map, you can incorporate a map function with specific criteria:

getDesiredAttributesById(inp_subCatid: string): Observable<any[]> {
  return this.subcategoryRef.snapshotChanges().pipe(
      take(1),
      map(changes => changes.map(c =>
        ({ key: c.payload.key, ...c.payload.val() })
      ).filter((subCat) =>
        subCat.catid === inp_subCatid
      ).map(({alcoholic,softdrinks,warmdrinks,...rest}) => ({
        alcoholic,softdrinks,warmdrinks
      })
    ));
  }

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

Sending a two-dimensional C array to Python NumPy

Could someone assist me in passing a C array to Python (numpy)? I have a 2D array of doubles with NumRows x NumInputs, but it seems that using PyArray_SimpleNewFromData is not converting it correctly. The debugger only shows pointers which makes it hard to ...

Developing an interactive website utilizing AngularJS, WCF Service, and SQL Server

Exploring the possibilities of creating a web application, I stumbled upon AngularJS. With plans to incorporate WCF Service and SQL Server into my project, I am intrigued by what these technologies can offer. I want to ensure that AngularJS aligns with my ...

The error "Call to a member function exports() on array" occurs when attempting to use the

As I attempt to send an array of values to the jobExport() collection, I encounter an error stating Call to a member function jobsExport() on array. I comprehend the necessity for the collection to be populated with modal collection value. However, my goal ...

Utilizing the Public Directory in Vite Compilation

One issue I encountered in my project with Vite version 2.9.7 is related to the handling of images stored in the public folder within the project's root directory. To import these images, I utilized Vite's import.meta.glob function, like so: imp ...

Angular route is completely unresponsive

I initiated the %a{"ng-click"=>"get_destinations(city)"} Nevertheless, it was supposed to direct me to the "destinations" controller, but that wasn't the case There are no errors in the web console – what could be ...

Component fails to trigger @click handler

.vue component <template> <div class="modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> Loading Files </div> < ...

What sets apart window.location.href from this.router.url?

I'm curious about the various methods of obtaining the current URL in Angular. For instance: this.router.url My main question is: What advantages does using this.router.url offer over simply using window.location? Could someone kindly provide an exp ...

Incorporating JSON into a ColdFusion program

I have a website that showcases different views for registered and non-registered users. I am currently redesigning the product navigation to make it easier to manage by using JSON format. My website is built on Mura CMS with ColdFusion. Although what I ...

Tips for attaching functions to a fresh SVG element with jQuery?

My jQuery code creates an <svg> element and appends it to a <div>. When I try to access the appended <svg> using each() after the append() function, the event handler doesn't work. However, if I create the <svg> element before ...

Integrate your React Native application with a Node.js backend on your local machine

My attempt to establish a connection between my react native app and my node.js app on a Windows system has hit a roadblock. While I am able to receive responses from the node API using Postman, the response from the react native app is coming back as unde ...

Determine in React whether a JSX Element is a descendant of a specific class

I am currently working with TypeScript and need to determine if a JSX.Element instance is a subclass of another React component. For instance, if I have a Vehicle component and a Car component that extends it, then when given a JSX.Element generated from ...

How can I extract values from a JSON array using PHP in the specified format?

I received an array from my Android developer colleague, and I need to extract the values of the key name from the array shown below: [ { "data":"[{\"name\":\"step 1 kdfhghdkgjdf\\nkjdhfgkjhdkjghd\\nkdfjhgkjdh ...

Leveraging ThemeProvider Parameters with Global Styled-Components

When working with styled-components, how can I access the props of the ThemeProvider in the context of global.js? For instance, in my theme.js file, I have ${props => props.theme.fonts.fontSize} set to a default font size of 16px. const theme = { ...

React Material UI issue: You cannot render objects as a React child. If you intended to display a group of children, make sure to use an array instead

I am encountering an issue with the code provided below and despite trying various fixes, I am unable to resolve it. componentDidMount() { axios.get('http://localhost:8080/home') .then((response) => { this.setState({ ...

Exploring the dynamic data loading feature in Vue 3 by fetching data from the server and displaying it using a v-for

I am encountering an issue where I want to display data dynamically from a database using a v-for loop. However, when I attempt to push new data into the array, they show correctly in a console.log() but do not reflect any changes in the template. I have ...

Prevent scrolling/touchmove events on mobile Safari under certain conditions

iOS 5 now supports native overflow: scroll functionality. I am trying to implement a feature where the touchmove event is disabled for elements that do not have the 'scrollable' class or their children. However, I am having trouble implementing ...

Updating the index of an array after storing an element in Java

Recently, I started delving into Java and decided to practice my skills by creating a simple bank program to manage customer accounts. At the beginning stages, I initialized an array named "accounts" of the Customer type, a class I created to store user in ...

Is it possible to convert the useMemo function into a useReducer hook implementation?

While I've figured out how to switch from using useState to useReducer, I'm now curious if there's a similar approach for transitioning from useMemo? I've been troubleshooting some code that's causing unnecessary renders because o ...

My goal is to prevent users from using the Backspace key within the input field

Let's say we want to prevent users from using the backspace key on an input field in this scenario. In our template, we pass the $event like so: <input (input)="onInput($event)"> Meanwhile, in our app.component.ts file, the function ...

Issues have been identified with the functionality of jQuery validation in MVC when applied to dynamically added elements

Although this issue has been addressed multiple times before, I am struggling to resolve it using the provided solutions. I am currently developing a basic library application. One of the features involves adding a copy of a book, which utilizes jQuery to ...