Reputation: 131
I have an array of objects, with each object looking like this:
var car = {
make: "",
model: "",
price: ""
}
I'm trying to loop through each object while looking to see if a specific property is defined like so:
for (i = 0; i <= 5; i++) {
if (obj[i].price == ""){
// empty
}
}
For some reason I keep getting the value as undefined. Is there a different/correct way to do what I am trying to do?
Upvotes: 0
Views: 114
Reputation: 9549
I'm trying to loop through each object ... to see if a specific property is defined
Here is an example of looping through an array of objects and printing whether or not a property is defined for each object. Just be careful with those truthiness checks, which are not the same thing as being "defined". You probably want to look at hasOwnProperty.
const cars = [
{ make : 'Toyota', model : 'Prius', price : 15000 },
{ make : 'Honda', model : 'Civic', price : 10000 },
{ make : 'Ford', model : 'Edsel', price : 0 }
];
cars.forEach((car) => {
console.log(`${car.make} ${car.model}:`);
if (car.hasOwnProperty('price')) {
console.log('Has a price.');
}
if (car.price) {
console.log('Costs some money.');
}
});
This will print:
Toyota Prius:
Has a price.
Costs some money.
Honda Civic:
Has a price.
Costs some money.
Ford Edsel:
Has a price.
The Ford Edsel has a price, but shouldn't cost any money.
Upvotes: 2