I am trying to console.log
the typeOne
(or any other type) property of each object in the donuts
array, but I keep getting undefined
as the output. My editor is showing that the problem is at the colon character in the object literals, suggesting that I should print a comma instead. However, I believe that is incorrect. What is the issue here and how can I fix it?
var donuts = [
{ typeOne: "Jelly", cost: 1.22 },
{ typeTwo: "Chocolate", cost: 2.45 },
{ typeThree: "Cider", cost: 1.59 },
{ typeFour: "Boston Cream", cost: 5.99 }
];
console.log(donuts.typeOne);
//or
console.log(donuts["typeOne"]); //both console.log shows undefined
4
Answers
In your example donuts is an array not an object (it’s an array of objects). To print the first item, you have to write donuts[0].typeOne. You are getting undefined because you are treating the donuts variable as an object instead of an array.
Hope it helps!
Because
donuts
is an array. You can reference items in an array by their indexes.For example:
You could make things are little more interesting if you change
type<Number>
toname
and do something like this:You are trying to access the property
typeOne
directly from donuts. But donuts is an array of objects, not a direct object. If you want to get the propertytypeOne
from each object in your array, you need to go at each item with some method likemap
:Problem is, the property
typeOne
only exists in the first object of your array, soresult
here will be ["Jelly", undefined, undefined, undefined]To list all types from each object in your array I suggest this:
In this case,
type
is a property in every object, so when you usemap
you iterate through all the objects in your array and get the value of the propertytype
.Hope it helps
So your object "typeOne", is an an array.
You have to access the object in the array, then the objects properties.