Problem
I\’m currently working in a chatbox project and
some of my data in firebase realtime database look like this:
let objUsers = {
\"123abc\": {
name: \"Dexter\",
age: 18,
},
\"456xyz\": {
name: \"Bob\",
age: 22,
},
};
Inspect
As you can see I probably need to put an userId to the object or
find a way to access to those data without typing my id as \”123abc\” or \”456xyz\” every times i need it.
If I try to change the object in realtime database to an array is gonna be something like this:
let arrayUsers = {
0: {
userId: \"123abc\",
name: \"Dexter\",
age: 18,
},
1: {
userId: \"456xyz\",
name: \"Bob\",
age: 22,
},
};
Solution
So I decide to lookup on the internet and here is two ways to convert the data in the way I want:
- Using Object.keys()
function convertObjectToArray() {
let objUsers = {
\"123abc\": {
name: \"Dexter\",
age: 18,
},
\"456xyz\": {
name: \"Bob\",
age: 22,
},
};
let userArr = [];
Object.keys(objUsers).forEach((key) =>
userArr.push({ userId: key, ...objUsers[key] })
);
console.log(userArr);
}
- Using Object.entries():
function convertObjectToArray() {
let objUsers = {
\"123abc\": {
name: \"Dexter\",
age: 18,
},
\"456xyz\": {
name: \"Bob\",
age: 22,
},
};
let userArr = Object.entries(objUsers).map((entry) => {
return { [\"userId\"]: entry[0], ...entry[1] };
});
console.log(userArr);
}
Output
And you can decide whatever the solutions you want Object.keys() or Object.entries() and
forEach() or map() but the output on these two is the same as I want:
userArr = [
{ id: \"123abc\", name: \"Dexter\", age: 18 },
{ id: \"456xyz\", name: \"Bob\", age: 22 },
];
More Examples
For more understanding you can look at these method of Object in JavaScript:
I have an object as below:
const hooman = {
firstName: \'Dexter\',
lastName: \'Duong\'
};
To get an array of property’s names:
const propertyNames = Object.keys(hooman);
console.log(propertyNames);
// [\"firstName\", \"lastName\"]
To get an array of property\’s values:
const propertyValues = Object.values(hooman);
console.log(propertyValues);
// [\"Dexter\", \"Duong\"]
Look at the result of Object.entries:
const entries = Object.entries(hooman);
console.log(hooman);
// [ [\"firstName\", \"Dexter\"] , [\"lastName\", \"Duong\"] ]
I found a phrase for this result as \”the enumerable string-keyed properties\”.
But I just call it an array of property\’s keys and value inside an array… lol
Conclusion
At this blog I will just talk about this small problem that I met along my journey, for more specialize about my chat box project using javascript and firebase realtime database, please hit a like and comment to motivate me to continue write another blog about it!
If you would like to read the code you can checkout my code in github/ gitlab profile below, if you have any questions please do not hesitate to contact me via email, thank you for reading!
Follow Me
github: https://github.com/thanhduy1512
gitlab: https://gitlab.com/duydt1512
mail: [email protected]
