Q:

Is it possible to loop through objects inside an object using for loops?

I'm trying to loop through one of my objects and get the objects inside that object.
In this example, I'm trying to loop through the items in the orderCart to get the qty and price
{ _id: 591327ea6325162512438858,
   orderCart: 
   { totalPrice: 66.95,
     totalQty: 5,
     items: 
      { '5900e2e1e2e75276ca68e10c': { item: [Object], qty: 2, price: 25.98 },
        '5900d8fde2e75276ca68e107': { item: [Object], qty: 2, price: 25.98 },
        '58fff1d322f00e71fdbfe422': { item: [Object], qty: 2, price: 25.98 }
      } 
   },
   orderEmail: 'email@gmail.com',
   orderFullName: 'John Doe'
}

Is it possible to do this with a for loop/forEach or is there another way of doing this?

A:

You can use for...in or you can iterate over Object.keys()

var myObj = {
  _id: "591327ea6325162512438858",
  orderCart: {
    totalPrice: 66.95,
    totalQty: 5,
    items: {
      '5900e2e1e2e75276ca68e10c': {
        item: [Object],
        qty: 2,
        price: 25.98
      },
      '5900d8fde2e75276ca68e107': {
        item: [Object],
        qty: 2,
        price: 25.98
      },
      '58fff1d322f00e71fdbfe422': {
        item: [Object],
        qty: 2,
        price: 25.98
      }
    }
  },
  orderEmail: 'email@gmail.com',
  orderFullName: 'John Doe'
};

console.log("---- for...in ----");
for (var key in myObj.orderCart.items) {
  if (myObj.orderCart.items.hasOwnProperty(key)) {
    var obj = myObj.orderCart.items[key];
    console.log(obj.qty, obj.price);
  }
}
console.log("---- Object.keys() ----");
Object.keys(myObj.orderCart.items).forEach(function(key) {
  var obj = myObj.orderCart.items[key];
  console.log(obj.qty, obj.price);
});

