user165242
user165242

Reputation: 1399

Javascript / Typescript : Flattening an Object accessed via firebase

I am trying to get data from a firebase database. I am getting the Object structure this way:

enter image description here

I want to be made this way:

enter image description here

Is there any elegant way of doing this in the frontend or is it better to make the changes in the tree structure in the database?

The only reason I have it in the current form, is that it makes it easier for me to form a tree hierarchy structure later on.

Upvotes: 0

Views: 117

Answers (1)

CRice
CRice

Reputation: 32186

You just have to do it manually, but thankfully it's not too hard. If snap is the firebase snapshot you are getting that includes postId/... as it's child, then:

const results = [];
snap.forEach(child => {
    child.forEach(grandchild => {
        results.push({
            id: child.key,
            uid: grandchild.key,
            ...grandchild.val(),
        });
    });
});

// Do stuff with results...

Upvotes: 1

Related Questions