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)
}]
}]
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'
}
})
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.