I have an array of cars and I need to check if the car exists in the object.
const cars = ["mustang", 'sonata'];
const carsObj = {
ford: "mustang",
audi: 'r8',
tesla: 'model 3'
};
What i did so far was to check but I only know how to do it with the first element in the array exists in the object. I am looking for the fastest way to this if possible.
carsObj[Object.keys(carsObj).find(key => carsObj[key] === cars[0])];
This should return mustang
because it is in the array and the object
Instead of checking cars [0] I need to check the entire array. Also, the array would never be that big. Maybe 5 elements the most. Is it better to loop thru the array of the object?
2 Answers 2
Use includes()
to search the whole array instead of just checking the first element.
Also, you can use Object.values()
instead of Object.keys()
, so you get the values directly, rather than having to write carsObj[key]
const cars = ["mustang", 'sonata'];
const carsObj = {
ford: "mustang",
audi: 'r8',
tesla: 'model 3'
};
console.log(Object.values(carsObj).find(val => cars.includes(val)))
you need just values of your object not keys:
let values = Object.values(carsObj);
it will give you array of values => [ mustang,r8,model 3] then use forEach method
cars.forEach((car)=> {
const found = values.find((value)=> value === car)
}