1

I have an array structured like this:

var myArray = [{ value1: "a", value2: "b" }, { value1: "c", value2: "d" }, { value1: "e", value2: "a" }];

From this array, I want to check if there is a 'value1' that has the value 'a' and have the function return true or false.

Is this possible, or will I have to loop through All the Objects, checking each value and then returning true/false?

Thanks!

asked Aug 18, 2021 at 8:16
3

3 Answers 3

2

You can use Array's some method for this.

var myArray = [{ value1: "a", value2: "b" }, { value1: "c", value2: "d" }, { value1: "e", value2: "a" }];
let out = myArray.some((ele)=>ele.value1 === "a")
console.log(out)

answered Aug 18, 2021 at 8:19
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the some array method like this:

myArray.some(el => el.value1 === 'a')

This will return true if there is such a value and false if not

answered Aug 18, 2021 at 8:19

Comments

0

You can use the array.find method to do that.

var myArray = [{ value1: "a", value2: "b" }, { value1: "c", value2: "d" }, { value1: "e", value2: "a" }];
console.log(!!myArray.find(element => element.value1 === "a"))

answered Aug 18, 2021 at 8:29

Comments

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.