1

For some reason, the result here is coming up as false, yet the array contains that particular dateId.

See code below:

var pollOptions = [
  {"dateId": "183738", "answer": false},
  {"dateId": "183738", "answer": true}
];

var theDate = "183738";
var doesDateExist = theDate in pollOptions


document.getElementById("demo").innerHTML = doesDateExist;
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
Darryl
  • 49
  • 5

3 Answers3

1

in operator works for objects (not on arrays). You can use .some() method to check the presence of a specific value in an array of objects:

var pollOptions = [
  {"dateId": "183738", "answer": false},
  {"dateId": "183738", "answer": true}
];

var theDate = "183738";
var doesDateExist = pollOptions.some(({ dateId }) => dateId === theDate);


document.getElementById("demo").innerHTML = doesDateExist;
<div id="demo"></div>
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
  • Thanks this is perfect :) If i wanted to get the "answer" value from the key I am searching for, how woild I do this? – Darryl Apr 08 '20 at 10:39
  • @DarrylBartlett You mean you will have this type of code? `theAnswer = false` – Mohammad Usman Apr 08 '20 at 10:49
  • @Mohammed Usman - Yeah that's right. So if I was searching for 183738, it would return the answer, for example false. – Darryl Apr 08 '20 at 10:50
  • @DarrylBartlett If you wants to find object with multiple search filters, you can check this post... https://stackoverflow.com/questions/31831651/javascript-filter-array-multiple-conditions – Mohammad Usman Apr 08 '20 at 10:54
1

You can use the .includes() method on an array rather an in`, which works on objects.

var pollOptions = [{"dateId": "183738", "answer": false}, {"dateId": "183738", "answer": true}];

var theDate = "183738";
var doesDateExist = pollOptions.map(item => item.dateId).includes(theDate);

document.getElementById("demo").innerHTML = doesDateExist;

Additionally, I use the .map() function to stream your object into an array only containing the dateIds. Then we can use .includes()

Shane Creedon
  • 1,573
  • 1
  • 14
  • 18
1

var pollOptions = [{"dateId": "183738", "answer": false}, {"dateId": "183738", "answer": true}];
var theDate = "183738";

var doesDateExist  = Boolean(pollOptions.find(function(item) {
   return item.dateId === theDate
}))

console.log(doesDateExist )
GoranLegenda
  • 491
  • 3
  • 9