0

I have an object with some propreties:

const carOptions = {
  mazda: 25000,  
  tesla: 85000,
  bmw: 100000
}

I would like to convert a for loop …

for (let i = 0; i < cars.length; i++) {
  if (cars[i].checked) {
    return carOptions[cars[i].id]
  }
}
…

… To .forEach but this code isn't working:

cars.forEach(function(cars)) {
  if (cars.checked) {
    return carOptions[cars.id]
  }
}
…

What am I missing?

Tzar
  • 5,132
  • 4
  • 23
  • 57
  • 1
    `forEach` doesn't work on objects. You could use `Object.keys(carOptions)` or `Option.values(carOptions)` – JanS Aug 31 '18 at 10:59
  • Possible duplicate of https://stackoverflow.com/questions/921789/how-to-loop-through-a-plain-javascript-object-with-the-objects-as-members – keul Aug 31 '18 at 10:59
  • Possible duplicate of [How to loop through a plain JavaScript object with the objects as members?](https://stackoverflow.com/questions/921789/how-to-loop-through-a-plain-javascript-object-with-the-objects-as-members) – keul Aug 31 '18 at 10:59
  • You ask about `cars` but your post starts with `carOptions`, and that's not an array. – Pointy Aug 31 '18 at 10:59
  • @Pointy That's not the array he's looping over, it's used inside the loop in `carOptions[cars[i].id]` – Barmar Aug 31 '18 at 11:02
  • @Barmar yes I've pieced it together, but `cars` should have been in the question obviously. – Pointy Aug 31 '18 at 11:02
  • @LucaFabbri That doesn't solve the problem. His problem is with how to return the result when he uses `forEach`. – Barmar Aug 31 '18 at 11:04

1 Answers1

4

The problem is that you're returning from the callback function, not the containing function.

You should set a variable in the forEach() callback, and then return that outside the loop.

var checkedOption;
cars.forEach(car => {
    if (car.checked) {
        checkedOption = carOptions[car.id];
    }
});
return checkedOption;

Note that this is not as efficient as the for loop. The loop will stop and return from the function as soon as it finds a match. But there's no way to stop forEach() in the middle, it will keep testing the remaining cars. And if there are multiple checked cars, checkedOption will be set to the options corresponding to the last one, not the first.

You could instead use .find():

var checkedCar = cars.find(car => car.checked);
if (checkedCar) {
    return carOptions[checkedCar.id];
}
Barmar
  • 741,623
  • 53
  • 500
  • 612