0

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?

14
  • What value is undefined? Commented Dec 27, 2016 at 16:50
  • How big is the array? i <= 5 is for an array with at least 6 elements. You should use i < obj.length. Commented Dec 27, 2016 at 16:51
  • if i were to just console.log(obj[0].price), or any index in my given range, I get undefined. Commented Dec 27, 2016 at 16:51
  • Can't you create a snippet to us? Commented Dec 27, 2016 at 16:52
  • give us whole array Commented Dec 27, 2016 at 16:53

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.