skip to Main Content

So I am creating a project using a Firebase database and React / Node.js to consult it.

I created a couple of entries via POST request like this:

const res = await fetch(`${MYFIREBASE}/posts.json`, {
    method: "POST",
    body: JSON.stringify(post)    
});

Then I consult these posts in another page like this:

const res = await fetch(`${MYFIREBASE}/posts.json`, { method: 'GET'});
const json = await res.json();
console.log(json)

And I get this result from it:

{
    '-O5NIwGpZU_GNQb75BPS': {
        post: [ [Object], [Object], [Object] ],
        name: 'name1'
    },
    '-O5NK_uGPJySPQo-ZmDF': {
        post: [ [Object], [Object] ],
        name: 'name2'
    }
}

Now my problem is, and I’ve been looking all over Google and this site to no use, how can I access my data (that is behind the autogenerated key as a tag), in my code?

Since this is an object I need the key to access the value but the key is an autogenerated value that I of course can’t know beforehand. I am feeling pretty lost with this.

I tried stupid things like json[0] and whatever I could think of, but it does not makes sense because that is not how objects properties are accessed. The only other solution I could think of is access the Object.keys(json) but it doesn’t make any sense that I have to use a workaround for something as simple as consulting all the entries on a document.

I tried reading (to be fair scanning) the firebase docs but they were no use or I missed the relevant sections.

2

Answers


  1. Object.keys itself is the best solution for your case. This is the best way because you don’t actually know the IDs of the documents you actually want to read.

    So it’s best to stick with something like this:

    // Get all keys
    const keys = Object.keys(json);
    
    // Iterate over keys
    keys.forEach(key => {
        console.log('Key:', key);
        console.log('Data for this key:', data[json]);
    });
    

    Hope this helps 🙂

    Login or Signup to reply.
  2. If you don’t want to use Object.keys (as VLAZ commented and the cosmic introvert dude answered), you can use a for in loop:

    for (const key in json) {
      console.log(key, json[key]);
    }
    

    Both approaches are equally idiomatic and give you the exact same result, the for in loop just doesn’t have to create a closure.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search