0

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!

CodingBoss
  • 37
  • 1
  • 6
  • 2
    Does this answer your question? [How to determine if Javascript array contains an object with an attribute that equals a given value?](https://stackoverflow.com/questions/8217419/how-to-determine-if-javascript-array-contains-an-object-with-an-attribute-that-e) – Ivar Aug 18 '21 at 08:19
  • 3
    `myArray.some(e => e.value1 === 'a')` – Ivar Aug 18 '21 at 08:19
  • Yes, Thanks! I did search around for a bit but I guess I didnt word it correctly. – CodingBoss Aug 18 '21 at 08:20

3 Answers3

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)
TechySharnav
  • 4,869
  • 2
  • 11
  • 29
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

Gabriel Lupu
  • 1,397
  • 1
  • 13
  • 29
-1

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"))
harisu
  • 1,376
  • 8
  • 17