One solution would be to map from the status number to the array property name, like this:
const arrayNameByStatus = { // This could be an array, but I wasn't sure if
0: "numOfActiveUsers", // status codes were necessarily contiguous like
1: "numOfInactiveUsers", // they are in the question
2: "numOfWaitingUsers",
3: "numOfAClosedUsers",
};
for (const obj of this.allClients) {
const name = arrayNameByStatus[obj.status];
if (name) { // Remove this for an error if status is an unexpected value
this[name].push(obj);
}
}
Live Example:
const arrayNameByStatus = {
0: "numOfActiveUsers",
1: "numOfInactiveUsers",
2: "numOfWaitingUsers",
3: "numOfAClosedUsers",
};
class Example {
constructor() {
this.allClients = [
{status: 0},
{status: 2},
{status: 2},
];
this.numOfActiveUsers = [];
this.numOfInactiveUsers = [];
this.numOfWaitingUsers = [];
this.numOfAClosedUsers = [];
}
method() {
for (const obj of this.allClients) {
const name = arrayNameByStatus[obj.status];
if (name) {
this[name].push(obj);
}
}
}
}
const e = new Example();
e.method();
console.log(e);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…