1

Hello I am doing a school assignment my main problem is as follows.

var objectQueue = {
                customers:[
                {name:"Phil", order:"coffee"},
                {name:"Sandy", order:"coffee"},
                {name:"Enrique", order:"sandwich"},
                {name:"Joe", order:"coffee"},
                {name:"Alex", order:"muffin"},
                {name:"Zoe", order:"chili"},
                {name:"Bahamut", order:"sandwich"},
                {name:"Rydia", order:"timbits"}
            ]
        };

I have this object, I need to know how to access each customer's order through a for loop. I can't get the loop to read each person's order. What would be the right way to do this?

This is where I am currently:

objectQueue[x]order

3 Answers3

1

Assuming x is a counter:

objectQueue.customers[x].order
Joseph
  • 117,725
  • 30
  • 181
  • 234
0

You first need to access the length of the customers and use that as your loop count, from there you can use 'i' your counter to access properties

for (i=0; i<objectQueue.customers.length; i++){
     console.log(objectQueue.customers[i]);
     console.log(objectQueue.customers[i].name);
     console.log(objectQueue.customers[i].order);
}
jsmartfo
  • 975
  • 7
  • 8
0

objectQueue has a property named customers, to access a simple property on a Javascript object, you can just use its name: objectQueue.customers

Then, customers has a array of objects. To access elements in a array, we use its index:

customers[0]

Since the elements in the list are maps/objects, we can access them via properties as well:

customers[0].name

Putting this all together we get:

objectQueue.customers[0].name

Almost everything in Javascript is an object, so it's a little misleading to differentiate between arrays and objects (since arrays ARE objects), but I'm assuming you can dig into those details later if you're interested. In the meantime, this should get you going.

Igor
  • 33,276
  • 14
  • 79
  • 112