I am using onSnapshot to get data from Firebase to my front end. I'm trying to convert one field on the document, which is an array of objects, into a true array on the front end.
I already know that Firebase stores this data as an array of objects with each object's key as the index of the would-be array: 0, 1, 2, ...
However, on the front end, for display purposes, I was hoping I could actually convert this into an array I can map over. The data is a userChats document for a chat app. See below:
{
"conversationid": "someConvoId",
"lastMessageCreatedAt": {
"nanoseconds": 0,
"seconds": 1598882400,
},
"lastMessageFromId": "someId",
"lastMessageFromName": "Guy",
"lastMessageText": "Hey, what up?",
"readByUser": false,
"usersArr": [
{
"userAvatar": "https://randomuser.me/api/portraits/men/65.jpg",
"userId": "someId",
"userName": "Guy",
},
{
"userAvatar": "https://randomuser.me/api/portraits/men/60.jpg",
"userId": "someOtherId",
"userName": "Gal",
},
],
}
The chat app uses group chat, so I'm using the usersArray to determine how many people are in the chat as well as display a user avatar, user name, and a "+1" (or +2, etc.) on the main Messages screen. In trying to convert the usersArray into a true array on the front end, I am getting unusual behavior. No matter what I try, methods that would work on either Objects or Arrays are rejected. Object.keys() only works for a console.log, but not when I try to assign the value to a variable.
const actuallyAnObject = chat.usersArray;
let realArray = actuallyAnObject.map((item, i) => item); // throws an error
console.log(Object.keys(actuallyAnObject); // displays in the console correctly
let keys = Object.keys(actuallyAnObject); // throws an error
let array = [];
Object.keys(actuallyAnObject).forEach((key) => { // throws an error
array.push({[key]: actuallyAnObject[key]});
});
console.log("actuallyAnObject['0'] : ", actuallyAnObject["0"]); // displays correctly
console.log("typeof actuallyAnObject : ", typeof actuallyAnObject); // object
How can I actually convert this into a useable array?
docsandforEach(), but is not actually an array. Can you use chat.usersArray.docs?usersArrbut in your example code it’susersArray. Is that just an oversight in the question?usersArray[0]should return all the values, and then you can iterate over those values to get key-pair for each user. So usersArray[0][0]["userAvatar"] would return the first avatar.