Transforming a collection of nested objects from Firebase into an array in JavaScript/Typescript

In my Ionic3 / Angular4 application, I am utilizing Firebase.

The structure of the data in Firebase Realtime Database is as follows:

Using the TypeScript code below, I am fetching observable data from Firebase...

getDishesCategories(uid: string) {

    // 1. Retrieve an observable AngularFire database snapshot

    const afDishCategoriesList$ = this.database.list<DishCategory>(`/users/${uid}/dishcategories/`).snapshotChanges()

    // 2. Transform the AF list into an observable list of dish category objects

    const dishCategoriesList$ = afDishCategoriesList$.pipe(map(changes => {
      return changes.map(c => ({
      ...c.payload.val()
      }))
    }))

    // 3. Return the observable list of dish objects

    return dishCategoriesList$
}

The output received is as follows:

[{
    createdDate: "2018-12-14T15:59:25.345Z",
    dishes: { ozvawkfci1dadyuibgdy4: {name: "Dish 1", selected: true} },
    id: "default01",
    name: "All Dishes",
    selected: true,
    toggleDisabled: true
}]

The challenge lies in receiving the 'dishes' data in JSON format, with Firebase key and object values.

I aim to convert the 'dishes' object of objects into a standard array for easy manipulation using methods like .length() and index access.

Desired output (with 'dishes' mapped to an array):

[{
    createdDate: "2018-12-14T15:59:25.345Z",
    dishes: [{name: "Dish 1", selected: true}],
    id: "default01",
    name: "All Dishes",
    selected: true,
    toggleDisabled: true
}]

I am struggling to achieve this transformation as I am new to .map() and despite spending hours on it, I can't figure it out!

Seeking assistance from anyone familiar with this. Thank you!

Answer №1

Here is a straightforward data manipulation process in JavaScript. Iterate through the properties of the object stored in dishes and create an array containing only the values of those properties. Subsequently, replace the original property with this new array. For every object o within the array, follow a pattern like this:

o.dishes = Object.keys(o.dishes).map(key => o.dishes[key])

If you are working with more recent JavaScript versions, you can achieve this more succinctly using

o.dishes = Object.values(o.dishes)
.

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

JS receiving a reference to an undefined variable from Flask

I referenced this helpful post on Stack Overflow to transfer data from Flask to a JS file. Flask: @app.route('/') def home(): content = "Hello" return render_template('index.html', content=content) HTML <head> ...

Modify a website link using Javascript by detecting two separate button clicks

I am seeking a way to dynamically change the src attribute of different images on a house depending on which button has been clicked. There are two groups of buttons: The types of house parts, such as windows, doors, garage, soffits, and gutters. The col ...

Try utilizing a variety of background hues for uib progressbars

Looking to incorporate the ui-bootstrap progressbar into my template in two different colors, background included. My initial idea was to stack two progress bars on top of each other, but it ended up looking too obvious and messy, especially in the corner ...

Converting Buffers to Binary with JavaScript Node.js

I've been working with Node.JS Buffers to send and receive packets, but I'm struggling to figure out how to convert these buffers into binary representation. I attempted the following code snippet, but it didn't yield the expected results co ...

Retrieving geographical data in GeoJSON format using AJAX request and displaying it on a Leaflet

I'm completely new to Leaflet and I'm struggling with how to integrate markers from a MySQL database onto a Leaflet map. Can anyone guide me on how to accomplish this using PHP and AJAX? .....{"type":"FeatureCollection","features":[{"geometry":{ ...

Combining and serializing a JavaScript object

Combining nested JavaScript objects was straightforward when dealing with a single object. However, as the number of objects has increased, I require a more dynamic approach to merge the address key and serialize my object. var old = {account: "100000 ...

What is the best way to add a dictionary to a JSON file without compromising the integrity of the JSON structure?

Before I explain my issue, I want to clarify that this is not a duplicated problem; it is unique. I am trying to add data to a dictionary within a JSON file using the code below. Please note that items like k['Process'] are sourced from another ...

Having trouble with installing create-react-app for my_app using npm because it seems to be stuck on f

I've hit a roadblock while trying to create a react app on my 2011 MacBook Pro. To start, I downloaded the latest version of Node from their official website. Following the instructions from React documentation, I ran the following commands: npm uni ...

Tips for retrieving specific information from a json file using xidel

Apologies for my non-native English I'm a beginner at this and still learning I have been attempting to retrieve specific values from a json file using xidel command in windows cmd, but I am facing issues xidel MyFile.json -e '$json//options/op ...

Generate a binary string using JavaScript and then transform it into C#

I have an upload section in my JavaScript program. I utilize JS FileReader to obtain a binary string of the uploaded document before sending it to my C# WebApi for storage on the server. JavaScript Code let myFile = ev.target.files[0]; if(myFile.size > ...

What is the best way to pinpoint the origin of the element.style being injected by JavaScript?

I've been tasked with updating a client's WordPress website, but I'm still getting acquainted with the overall structure of the site. When looking at the blog page (), I noticed that posts are displayed within a wrapper labeled #blogleft, a ...

The process of a ReactJS component's lifecycle is affected when an onClick event triggers a fetch function, causing the state

For the past week, I've been grappling with a coding challenge. My goal is to create a basic Pokedex featuring the original 151 Pokemon. The list of Pokemon should be displayed on the right side of the screen, pulled directly from a .json file copied ...

Meteor JS: How can I effectively manage the state of a unique template?

I'm currently delving into the realms of Session and reactive data sources within the Meteor JS framework. They prove to be quite useful for managing global UI states. However, I've encountered a challenge in scoping them to a specific instance o ...

React is unable to identify the `InputProps` prop when applied to a DOM element

https://i.sstatic.net/7fZmn.png Caution: React is not able to identify the InputProps property on a DOM element. If you intend for it to be displayed in the DOM as a custom attribute, spell it in lowercase as inputprops. If you accidentally passed it from ...

Kubernetes Cluster Encountering Error with Google FCM Firebase-Admin initializeApp() Function

Currently, I am in the process of setting up a NodeJs server and integrating FCM for push notifications. While everything runs smoothly locally, I encounter an error when running on my K8S cluster. An issue arises with FirebaseAppError: The credential impl ...

Utilize AngularJS to modify the appearance of text

Just starting out with AngularJS and I need to achieve the following task. I have a text that says "bob" and two buttons, one for bold and one for italic. When the bold button is clicked, I want to make the text BOB bold and when the italic button is click ...

How to retrieve a DOM element using Aurelia framework

When it comes to accessing a DOM element in Aurelia, what are the best practices to follow for different use cases? Currently, I have two scenarios in my Aurelia project: Firstly, within the template, there is a form that I need to access from the view-mo ...

Building protected "exclusive website sections" utilizing near-serverless website structure (AJAX template wizardry)

At the outset, I apologize if my English is not up to par; I will do my best to be as clear as possible. I am in the process of planning a web site with the following architecture: The site will consist of static pages served to clients using JavaScript t ...

Converting a string into a Date in Typescript while disregarding the timezone

Upon receiving a date in string format like this (e.g.): "11/10/2015 10:00:00" It's important to note that this is in UTC time. However, when creating a Date object from this string, it defaults to local time: let time = "11/10/2015 10:00:00"; let ...

Tips for maintaining a database connection pool in hooks.server.js while utilizing hot reload in SvelteKit using Vite.js and mariadb

I'm currently utilizing SvelteKit, Vite.js, and the mariadb package with Node.js in my application. In my db.js file, I have the code snippet below: import mariadb from 'mariadb'; const databaseConnectionPoolConfig = { ... }; let databas ...