DEV Community

Julie Gladden
Julie Gladden

Posted on

How to display nested data when using Angular + Firebase

Hello, everyone.

I've been working on a project recently, and I've been excited to try out Firebase as my backend.

I'm working on a project right now that's essentially an online 'practice log' for musicians. A way to track your practicing hours, skills, and even offer a few practice tools along the way.

Image description

Anyways, let's get into the project... When I started fetching my data that I'd stored in Firebase's realtime database, I noticed a glaring issue right away.

Instead of sending an an array inside of an array, the data sends back as objects of key value pairs that are nested inside of the array.

Key -> { 0, 'Coding is hard' } <- Value
The key is 0, the value is 'Coding is hard'.
Key value pairs are beneficial for scalability, speed, and numerous other things.

Now, one thing to note, is that if you are looping through data in Angular, using an *ngFor, the data MUST be in an array.

This is how the data presents in the realtime database:
Image description

And here it is printed to the console:

Image description

You can see that the fields 'skills' and 'instruments' are not arrays. They are an object with multiple key value pairs.

My data from Firebase is being held in a variable called 'logList'.

logList: Log[];

myFunction() {
  this.logList.forEach((log) => {
        log.skills = Object.values(log.skills);
        log.instruments = Object.values(log.instruments);
Enter fullscreen mode Exit fullscreen mode
  1. Target logList and get each item from its array separately using forEach.
  2. Take only the value part of each key value pair using the javascript 'Object.values' method.


The Object keys functions are so helpful!
Object.values() gets the value out of the key value pair.
Object.keys() gets the key out of the key value pair.

Now my data looks like this:

Image description

You can see the array [] surrounding 'skills' and 'instruments' now, instead of object {}.

So now I can display this data like so:

Image description

I tried to keep this pretty simple, so if you have any questions specifically leave a comment below! Also, google is awesome and should be your best friend. :-)

What do you want to see next?

Thank you for reading! - Julie

Top comments (0)