Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the whole object pushed in to an array from firebase Javascript

Im doing a simple webstore. I have products in firebase database that im fetching. I get the data as an object from firebase. But I want it to be an array with objects so I can use array methods like find(). The reason is that I want to add the given product to the cart when pushing the button and the function runs. Its the right product that adds when get clicked on but I dont get its all information as an object.

//add to cart array
  let cart = []

  //add to cart function
  function addToCart(id){
    async function getAndAddToCart(){
    const baseURL = 'https://webstore-22fa4-default-rtdb.europe-west1.firebasedatabase.app/'
    const url = baseURL + 'Products.json'
    const response = await fetch(url)
    let data = await response.json()

      const item = Object.keys(data).find(i =>data[i].id === id)
      console.log(item)
      cart.push(item)
      console.log(cart)
    }
    getAndAddToCart()
}  

1.console log(data)
2.console.log(item)
3.console log(cart)
enter image description here

I have tried with pushing data into and array. Object.keys seems to be the best way but It only returns the object name not the hole object with all information within. And when it pushes into an array its only the object name not the whole object.
The hole object should be pushed into the array not only product1, product2 etc.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Object.keys will return an array of object keys, which in your case seems to be ids. So your attempt Object.keys(data).find(i =>data[i].id === id) roughly translates to:

['1', '2', '3'...].find(i => data[i].id === id)

But you’re using find on the array of ids, so when it matches it gives you back an id from the array.

What you want is to either use the object directly:

const yourProduct = data[id];

Or use the Object.values() function:

const arrayOfProductObjects = Object.values(data);
const theProductToAdd = arrayOfProductObjects.find(product => product.id === id);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading