CodingBoss
CodingBoss

Reputation: 37

Find Key value from Array of Objects

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!

Upvotes: 0

Views: 68

Answers (3)

harisu
harisu

Reputation: 1416

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

Upvotes: -1

Gabriel Lupu
Gabriel Lupu

Reputation: 1447

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

Upvotes: 1

TechySharnav
TechySharnav

Reputation: 5084

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)

Upvotes: 2

Related Questions