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;

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks this is perfect :) If i wanted to get the "answer" value from the key I am searching for, how woild I do this?
@DarrylBartlett You mean you will have this type of code? theAnswer = false
@Mohammed Usman - Yeah that's right. So if I was searching for 183738, it would return the answer, for example false.
@DarrylBartlett If you wants to find object with multiple search filters, you can check this post... stackoverflow.com/questions/31831651/…
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()

2 Comments

How could I get the "answer" out of this query as well?
What do you mean? it returns true / false as you specifed
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 )

Comments

Your Answer

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.