2

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)});
2

3 Answers 3

6

Check out this answer.

const array = [];

Object.keys(yourObject).forEach((key) => {
  array.push({[key]: object1[key]});
});
Sign up to request clarification or add additional context in comments.

3 Comments

I managed to convert it to an array. But when i console log, there is a slight difference and my application is not receiving the data. I am getting: [] 0: {id: "r1", name: "Room 1"} 2: {id: "r2", name" "Room 2"} 3: {id: "r3", name" "Room 3"} but what I should be getting is: (3) [{...}, {...}, {...}] 0: {id: "r1", name: "Room 1"} 2: {id: "r2", name" "Room 2"} 3: {id: "r3", name" "Room 3"} The difference is in the first row of code. Is that the reason why my application is not receiving the data?
hello, I've managed to pass my data over already! thank you for your help :)
Nice that you solved it by yourself! Making progress :)
4

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]} 
});

2 Comments

managed to convert it to an array. But when i console log, there is a slight difference and my application is not receiving the data. I am getting: [] 0: {id: "r1", name: "Room 1"} 2: {id: "r2", name" "Room 2"} 3: {id: "r3", name" "Room 3"} but what I should be getting is: (3) [{...}, {...}, {...}] 0: {id: "r1", name: "Room 1"} 2: {id: "r2", name" "Room 2"} 3: {id: "r3", name" "Room 3"} The difference is in the first row of code. Is that the reason why my application is not receiving the data? Im trying to convert the firebase object to an array via axios.
hello, I've managed to pass my data over already! thank you for your help :)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.