0

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?

Olian04
6,9022 gold badges31 silver badges56 bronze badges
asked Apr 28, 2021 at 18:57

2 Answers 2

7

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)))

answered Apr 28, 2021 at 19:00
0

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)
}
answered Apr 28, 2021 at 19:18

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.