Ali Alsaggaf
Ali Alsaggaf

Reputation: 81

How to read real time database array child

How to read array data inside a child?

this my database

enter image description here

I tried get amount,image,price,title by using this method :

  var leadsRef = database.ref('items-ordered');
  leadsRef.on('value', function(snapshot) {       
      snapshot.forEach(childSnapshot => {
          console.log(childSnapshot.val().cart.amount);

the result I'm getting (undefined)

Upvotes: 0

Views: 95

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50830

cart here seems to be an array so you would have to loop over each item in the cart.

const cart = childSnapshot.val().cart

if (Array.isArray(cart)) {
  cart.forEach(item => console.log(item))
} else {
  Object.keys(cart).forEach((key) => console.log(cart[key]))
}

The reason why I am checking if cart is an array (or otherwise a map) can be found in this blog.

Upvotes: 1

Related Questions