how to compare js array values with a string
I have a JSON array and I want to compare its values with a String. For Example, My JSON Array is
{ "slot": ["10:00 AM", "10:30 AM", "03:30 PM"] }
Now I am trying to access it in this way:
for (i in data.slot) { console.log(slot[i] === "10:00 AM"); //this return false if (slot[i] === "10:00 AM") btn1.disabled = true; if (slot[i] === "10:30 AM") btn2.disabled = true; if (slot[i] === "03:00 PM") btn3.disabled = true; if (slot[i] === "03:30 PM") btn4.disabled = true; }
Now whenever I am trying to compare it, the if statement returns false and the button doesn’t get disabled. I got to know this on the Chrome Dev console. Any Suggestions would be appreciated.
Answer
You need to address the right variable
data.slot[i] ^^^^^
const data = { slot: ["10:00 AM", "10:30 AM", "03:30 PM"] } for (let i in data.slot) { console.log(data.slot[i] === "10:00 AM"); // true false false if (data.slot[i] === "10:00 AM") btn1.disabled = true; if (data.slot[i] === "10:30 AM") btn2.disabled = true; if (data.slot[i] === "03:00 PM") btn3.disabled = true; if (data.slot[i] === "03:30 PM") btn4.disabled = true; }
<button id="btn1">1</button> <button id="btn2">2</button> <button id="btn3">3</button> <button id="btn4">4</button>
A better approach takes the value directly by iterating with for ... of
statement
const data = { slot: ["10:00 AM", "10:30 AM", "03:30 PM"] } for (const value of data.slot) { console.log(value === "10:00 AM"); // true false false if (value === "10:00 AM") btn1.disabled = true; if (value === "10:30 AM") btn2.disabled = true; if (value === "03:00 PM") btn3.disabled = true; if (value === "03:30 PM") btn4.disabled = true; }
<button id="btn1">1</button> <button id="btn2">2</button> <button id="btn3">3</button> <button id="btn4">4</button>