0

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?

0

1 Answer 1

1

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");}

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

3 Comments

this solution is partially correct. this if and else should only execute one scenario. If the label is "Required scenario only" then it should run doSomething() and console the text only 1 time and should not run 'else' scenario. if there is no 'Required scenario only' label in the array then and then only it should go to else and run 'doSomethingElse()' for only one time. The way the above code is running is, that it will run if and else both for each and every item of the array. it should not do that. one-time execution.
if no 'Required scenario only' is there then the else part should not check the other 3 scenarios and console the result 3 times it should run it only one time for all 3 cases and console the result 'Do Something Else' one time.
Did you run the snippet? Only one of the functions is run. It doesn't run both if and else; they are mutually exclusive by definition. If "Required scenario only" exists (determined by list.some(...)), then doSomething() runs. If "Required scenario only" doesn't exist, then doSomethingElse() runs.

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.