I try to check value statusC and add new value for statusP with process: If all statusC = ACCEPTED => statusP = ACCEPTED, if all statusC = REJECTED=> statusP = REJECTED, else status C have 2 value ACCEPTED and REJECTED = > StatusP = COMPLETED
- Declare Enum type use all
enum Status {
INPROGRESS = "INPROGRESS",
ACCEPTED = "ACCEPTED",
REJECTED= "REJECTED",
COMPLETED = "COMPLETED"
}
- Declare a:
let a= [
{
name:"test 1",
statusP : Status.INPROGRESS,
detail:[
{
nameC: "Test 2",
statusC: Status.REJECTED
},
{
nameC: "Test 3",
statusC: Status.ACCEPTED
}
]
}
];
- check statusC and add new value for statusP*
const checkStatusC = a[0].detail.map(
(item)=>{
let b;
b = item.statusC;
if(b===Status.ACCEPTED){
a[0].statusP = Status.ACCEPTED
}else if (b === Status.REJECTED){
a[0].statusP = Status.REJECTED
} else if({?}){
a[0].statusP = Status.COMPLETED
}
}
)
Please have me condition at {?}
CodePudding user response:
You shouldn't use map
in this case, map
is for mapping current items to new items (an array). If you want to set a new value or new values, you can use reduce
instead.
a[0].statusP = a[0].detail.reduce(
(result, item)=>{
//stop further checking for status P
if(result === Status.COMPLETED) {
return result;
}
//the current result of status P is different from status C
if(result && result !== Status.INPROGRESS && result !== item.statusC){
result = Status.COMPLETED;
} else {
result = item.statusC; //REJECTED or ACCEPTED
}
return result;
}
, a[0].statusP) //default value from status P
You also can use the traditional iteration for-of
which is more effective with a proper break
.
for(const item of a[0].detail) {
//the current result D is different from status C
if(a[0].statusP && a[0].statusP !== Status.INPROGRESS && a[0].statusP !== item.statusC){
a[0].statusP = Status.COMPLETED;
break; //stop further checking
} else {
a[0].statusP = item.statusC; //REJECTED or ACCEPTED
}
}