0

I have to find an object from an array of objects if the object is found then I have to add sort property to it, if it is not found then I am looking for another object. but if all the objects are present then I have to add sort property to first match only. I am using the switch case to achieve this. but if all the objects are present the sort property is added to all the objects. could anyone please tell me how can I achieve this?

Below is my code.

this.columns = this.columns.map(field) => {
            delete field.id;
            switch (field.name) {
                case 'creationTime':
                    field.sort = 'asc';
                    break;
                case 'priority':
                    field.sort = 'asc';
                    break;
                case 'completionTime':
                    field.sort = 'asc';
                    break;
            }
            return field;
        });
3
  • What do you mean by this but if all the objects are present then I have to add sort property to first match only Commented Mar 23, 2021 at 4:05
  • @RifatBinReza means if all the three cases are matched i have to add sort property to ist case Commented Mar 23, 2021 at 4:17
  • Then you cannot assign the column right away. You have to loop through the array to find if all three matches are there first Commented Mar 23, 2021 at 4:37

2 Answers 2

1

You can do it like this. Add a variable 'match' and assign it a value 'false'. Than wrapp the switch with a condition which check's if match isn't true. If one object matches than the variable is reassigned to 'true'.

let match = false;

this.columns = this.columns.map(field) => {
  delete field.id;
  if (!match) {
    switch (field.name) {
       case 'creationTime':
          field.sort = 'asc';
          match = true;
          break;
       case 'priority':
          field.sort = 'asc';
          match = true;
          break;
       case 'completionTime':
          field.sort = 'asc';
          match = true;
          break;
    }
  }
  return field;
});
Sign up to request clarification or add additional context in comments.

Comments

0

array.map() doesn't let you exit the loop while it is in progress. So I think a for loop might work better here.

However, you cannot break a loop from inside a switch without using a temporary variable. It is easier if you can avoid using a switch:

for (const field of this.columns) {
  if (field.name == "creationTime" || field.name == "priority" || field.name == "completionTime") {
    field.sort = "asc";
    break; // Exit the loop after first match
  }
}

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.