Reputation: 69
i need to display confirm message using vuejs that if contains true field in data field that data coming from an api.i have given api outpt below and also if condition that is used to display alert message. in below output there is no true. whenever true data comes then only alert should be displayed.
//API Data
{
"BNG-JAY-137-003": false,
"BNG-JAY-137-004": false,
"BNG-JAY-137-005": false
}
//below is my if condition and i am storing API output to an vaiable 'selected_data'
if(this.selected_data){
if(confirm("Do you want to Turn On All lights")){
alert("Lights on")
}
}
Upvotes: 0
Views: 458
Reputation: 593
Try confirm
. It should always return a boolean which you can then apply to your logic. COmbine it with Object.values()
function checkAndConfirm(object) {
result = true;
for (let key in Object.values(object))
result = Object.values(object)[key] && result;
if (result) {
let confirmed = confirm("Do you want to turn on all lights?");
if (confirmed) alert("Lights on")
}
}
checkAndConfirm({ //should evaluate as false
"BNG-JAY-137-003": false,
"BNG-JAY-137-004": true,
"BNG-JAY-137-005": true
});
checkAndConfirm({ //should evaluate as true
"BNG-JAY-137-003": true,
"BNG-JAY-137-004": true,
"BNG-JAY-137-005": true
});
Upvotes: 0
Reputation: 10009
You need to loop through your object to determine if any of the property contains true
as a value. You can achieve this by doing something like this:
let data = {
"BNG-JAY-137-003": false,
"BNG-JAY-137-004": true,
"BNG-JAY-137-005": false
};
let hasTrue = false;
for(let key in data) {
if(data[key]) {
hasTrue = true;
break;
}
}
if(hasTrue) {
if(confirm("Do you want to Turn On All lights")){
alert("Lights on");
}
}
Upvotes: 1
Reputation: 6978
Try this.
if (Object.keys(selected_data).map(function(item) {
return selected_data[item]}).indexOf(true) >=0) {
if(confirm("Do you want to Turn On All lights")) {
alert("Lights on")
}
}
}
Upvotes: 1