-3

I have 2 Objects in an array with 2 scenarios:

If test_status_id is accepted for all objects in array, then case_status_id should be completed, otherwise case_status_id should be pending. How do I go about doing that?

const result = [{
                     id:1,
                     case_status_id : 1(pending),
                     case_test_map : [{
                                           id:1,
                                           test_status_id: 1(accepted)
                                      },
                                      {
                                           id:2,
                                           test_status_id: 2(rejected)
                                      }]
                 },
                 {
                     id:2,
                     case_status_id : 2(completed),
                     case_test_map : [{
                                           id:1,
                                           test_status_id: 1(accepted)
                                      },
                                      {
                                           id:2,
                                           test_status_id: 1(accepted)
                                      }]
                 }]
Mike
  • 627
  • 1
  • 7
  • 21
Rekha
  • 433
  • 7
  • 22

2 Answers2

0

Try this

result.forEach(res => {
    const resultStatuses = res.case_test_map.map(test => test.test_status_id);
    if(resultStatuses.every( (val, i, arr) => val === arr[0] ) ) {
        if(resultStatuses[0] === 'accepted') {
            res.case_status_id = 'accepted'
        }
    }
    else {
        res.case_status_id = 'pending'
    }
})

sources: Check if all values of array are equal

vjanovec
  • 16
  • 4
0

Try the following function, it does what you need:

function calculateCaseStatus(result) {

  // at first, iterate over each element of result array
  for(let res of result) {

    // assume, 'case_status_id' would be set to 2 by default(i.e. 'completed')
    let flag = true;

    // now, check if any 'test_status_id' is set to 2(i.e. rejected)
    // for that, first iterate over each element of 'case_test_map' array
    for(let cmp of res.case_test_map) {

      if(cmp.test_status_id !== 1) {
        // if any test_status_id is not completed, then
        // case_status_id can't be 2(i.e. completed)
        // so, make the flag false
        flag = false;
        break;
      }
    }

    // if flag is true, set case_status_id to 2 (i.e. completed)
    if(flag) {
      res.case_status_id = 2;
    } else {
      // else set case_status_id to 1 i.e.(pending)
      res.case_status_id = 1;
    }
  }
}

You've to call it like:

calculateCaseStatus(result);

// and to check the result
console.log(result);
reyad
  • 1,392
  • 2
  • 7
  • 12