Reputation: 4253
I have a query that get post key in /Feed/, and then get the /posts/ by this keys.
snapshot.forEach((subChild) => {
var value = subChild.val();
value = value.postID;
var post = firebase.database().ref('/posts/' + value).orderByKey();
promises.push(new Promise((res, rej) => {
post.on('value', function(snapshot2) {
console.log(snapshot2.val());
res(snapshot2.val());
});
}));
});
let postsArray = await Promise.all(promises);
setPosts(prevPosts => {
return [
...prevPosts,
...Object.keys(postsArray).reverse().map(key => ({
key: key, ...postsArray[key]
}))
];
it return objects like this:
{id: 2, img: "src/img.jpg", title: "some text", user: "username_01"}
I'd like firebase to return the post key too. What can I do?
posts
|
----M5HMGsA3YyW_NJfSV (wanna this value in object too)
|
----id: 2
|
----img: src/img.jpg
|
----title: some text
|
----user: username_01
Upvotes: 0
Views: 140
Reputation: 73896
A snapshot2 key
is the property of snapshot2
object, so you can easily access it like:
post.on('value', function(snapshot2) {
console.log(snapshot2.key);
});
Now, as you need to merge this key to return response, you can simply do this using the Object.assign()
method like:
post.on('value', function(snapshot2) {
var obj = Object.assign(snapshot2.val(), { _key: snapshot2.key });
console.log( obj );
res( obj );
});
Upvotes: 1
Reputation: 717
You can get the key like that:
snapshot2.key
If you want to place it to your object, you have to push that value too to your array.
Upvotes: 0