Joey
Joey

Reputation: 47

How to convert firebase object to array?

I am using firebase with axios. I need to convert this Object:

{r1: "Room 1", r2: "Room 2", r3: "Room 3"}

Into an Array:

rooms = [
    { id: 'r1', name: 'Room 1'},
    { id: 'r2', name: 'Room 2'},
    { id: 'r3', name: 'Room 3'},
];

Currenltly, I cam calling from firebase with axious like this:

axios.get('firebaseURL').then(response => {console.log(response.data)});

Upvotes: 2

Views: 8686

Answers (3)

DSCH
DSCH

Reputation: 2366

You can use Object.keys(rooms) with map() - The Object.keys returns an array with all the object keys, and the map function accepts each key, and will return whatever you make of that key into a new array. So in the snippet below Object.keys(rooms) is equal to [ 'r1', 'r2', 'r3' ] and from that it is easy to construct your desired array.

const rooms = {r1: "Room 1", r2: "Room 2", r3: "Room 3"};

const arrayResult = Object.keys(rooms).map(room => {
    return {id: room, name: rooms[room]} 
});

Upvotes: 4

Oluwatobi Shokunbi
Oluwatobi Shokunbi

Reputation: 11

you can try this using this package https://github.com/just1and0/object-to-array-convert

import { O2A } from 'object-to-array-convert';

const rooms = {r1: "Room 1", r2: "Room 2", r3: "Room 3"};

const value = O2A(rooms);

return value

Upvotes: 1

Tsuni
Tsuni

Reputation: 5798

Check out this answer.

const array = [];

Object.keys(yourObject).forEach((key) => {
  array.push({[key]: object1[key]});
});

Upvotes: 6

Related Questions