Reputation: 453
I have a simple question today.
I retrieve data from my firebase database:
const response = await fetch('For pricacy purpose I replaced this link to my firebase database.');
const resData = await response.json();
console.log(resData);
Also I log the results in the console, the following text is what I retrieve:
Object { "-MPOg49jvG-md0twgj-D": Object { "id": 1, }, "-MPTgHoTXzIcY_KpBHkc": Object { "id": 2, }, "-MPTgmANDZkMv7f_A9TG": Object { "id": 4, }, "-MPTgmc2fuu5XSUawuW7": Object { "id": 3, }, }
Now my question: I want to access not the id that is in the objects but rather the "name" of the object itself. If you look at the first element:
"-MPOg49jvG-md0twgj-D": Object { "id": 1, }
i want to access this "-MPOg49jvG-md0twgj-D" and store it in a constant but I dont know how to do it. Any idea would be appriciated.
Upvotes: 1
Views: 215
Reputation: 1009
If I'm understanding correctly, you already fetched resData
as a JavaScript object and want to get the keys? These are some ways that possibly could help you.
const resData = {
"-MPOg49jvG-md0twgj-D": {
id: 1
},
"-MPTgHoTXzIcY_KpBHkc": {
id: 2
},
"-MPTgmANDZkMv7f_A9TG": {
id: 4
},
"-MPTgmc2fuu5XSUawuW7": {
id: 3
}
};
// method 1
console.log(Object.keys(resData));
// method 2
for (const key in resData) {
console.log(key, resData[key]);
}
// method 3
console.log(Object.getOwnPropertyNames(resData));
Hope this can help, please correct me if I got it wrong.
Upvotes: 3