I have an array of object like this
list = [
{
"label" : "whatever",
"value" : "value 1"
},
{
"label" : "whatever",
"value" : "value 2"
},
{
"label" : "Required scenario only",
"value" : "value 3"
},
{
"label" : "whatever",
"value" : "value 4"
},
]
I am running for a loop with conditions, I want to execute some piece of code only for one scenario called 'Required scenario only' for the rest of all scenarios run different code for only one time, it should not execute 3 times as per loop executes
for(i=0; i< list.length; i++) {
if(list[i].label === 'Required scenario only' ) {
//execute some code
} else {
// execute code for 1 time for rest of the labels i.e for all 'whatever' scenarios
}
}
How should I do it?
If you're merely checking for the existence of an object with label = "Required scenario only" then I would use Array.some():
list = [{
label: "whatever",
value: "value 1"
},
{
label: "whatever",
value: "value 2"
},
{
label: "Required scenario only",
value: "value 3"
},
{
label: "whatever",
value: "value 2"
},
]
if (list.some(l => (l.label == "Required scenario only"))) {doSomething();}
else {doSomethingElse();}
function doSomething() {console.log("Do Something");}
function doSomethingElse() {console.log("Do Something Else");}