Q: node express loop through session data I have data in a user session (not saved to a database yet) that I need to query.  I am looking to get the quantity value for each of the 3 items below, for example, I'm looking to retrieve 1 for the quantity from { prod: [Object], price: 100, quantity: 1 } 
how can I loop through the session data and retrieve the quantities?
{ products:
   { '5c60c83e84555d391aaca89b': { prod: [Object], price: 100, quantity: 1 },
     '5c60d6cd3351283d13a9f463': { prod: [Object], price: 150, quantity: 2 },
     '5c60da303351283d13a9f464': { prod: [Object], price:10, quantity: 2 } },
  cartQty: 5,
  cartTotal: 420 }

I've tried this which gives me the id's like 5c60c83e84555d391aaca89b
    var sp = sessionCart.products;
    for (var p in sp) {
        console.log(p);
    } 

I get nothing for output when I try this
         Array.from(sessionCart.products).forEach(function (child) {
             console.log(child);
         });


A: You can change your for...in loop slightly to show the quantity:


var sessionCart = {
  products: {
    '5c60c83e84555d391aaca89b': {
      prod: [Object],
      price: 100,
      quantity: 1
    },
    '5c60d6cd3351283d13a9f463': {
      prod: [Object],
      price: 150,
      quantity: 2
    },
    '5c60da303351283d13a9f464': {
      prod: [Object],
      price: 10,
      quantity: 2
    }
  },
  cartQty: 5,
  cartTotal: 420
}

var sp = sessionCart.products;
for (var p in sp) {
  console.log(sp[p].quantity);
}


Alternatively, use an iteration over Object.values and destructuring like so:


var sessionCart = {
  products: {
    '5c60c83e84555d391aaca89b': {
      prod: [Object],
      price: 100,
      quantity: 1
    },
    '5c60d6cd3351283d13a9f463': {
      prod: [Object],
      price: 150,
      quantity: 2
    },
    '5c60da303351283d13a9f464': {
      prod: [Object],
      price: 10,
      quantity: 2
    }
  },
  cartQty: 5,
  cartTotal: 420
};

Object.values(sessionCart.products).forEach(({ quantity }) => console.log(quantity));



A: The crux of your problem is that you're trying to loop through the values of an object and pull out a property (quantity) of each object.
You could use Object.values() to get just the values of the object as an array and loop through that.
Object.values(sessionCart.products).forEach(function (product) {
  console.log(product.quantity)
})

