4

I have an array, like so:

 const myArray = [{key1: "value1", key2: "value2"}, {key1: "value4", key2: "value8"},
  {key1: "value1", key2: "value3"}, {key1: "value1", key2: "value32"}]

I need to loop through the array, and see if ANY item in the array has a certain value. I have looked through other questions and most loop through and create variables, however I am not allowed to use var (ES6 something, I'm a js noob and am not sure, just was told to never use var, always const). Basically I need something like this:

if (myArray.contains(object where key1=="value2")) {
  // do something
}

I would like for the function to return true/false as well, not the object itself.

thanks

jjjjjjjj
  • 4,203
  • 11
  • 53
  • 72
  • 2
    `myArray.some(o => o.key1 == 'value2')`… https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some – deceze May 08 '17 at 11:32
  • 2
    Another possible duplicate: http://stackoverflow.com/questions/22844560/check-if-object-value-exists-within-a-javascript-array-of-objects-and-if-not-add – Rajesh May 08 '17 at 11:35
  • 1
    @deceze Not sure how you think the question you linked is a duplicate. This question is about a dict, the other is about an array. Pretty obviously distinct. I wish Stack let people flag closures/duplicate marks. – Prime624 Jul 08 '19 at 16:37

3 Answers3

17

To check if object exists in array you can use some() that returns true/false

const myArray = [{key1: "value1", key2: "value2"}, {key1: "value4", key2: "value8"}, {key1: "value1", key2: "value3"}, {key1: "value1", key2: "value32"}]
  
if(myArray.some(e => e.key1 == 'value1')) {
  console.log('Exists');
}
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
4

Simply use with Array#map and includes()

 const myArray = [{key1: "value1", key2: "value2"}, {key1: "value4", key2: "value8"}, {key1: "value1", key2: "value3"}, {key1: "value1", key2: "value32"}]
console.log(myArray.map(a=>a.key1).includes('value2'))
prasanth
  • 22,145
  • 4
  • 29
  • 53
3

You can use Array.prototype.some().

Code:

const myArray = [{key1: "value1", key2: "value2"}, {key1: "value4", key2: "value8"}, {key1: "value1", key2: "value3"}, {key1: "value1", key2: "value32"}]

const isKey1Value2 = myArray.some(el => 'value2' === el.key1)

console.log(isKey1Value2)
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46