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);
But, if you're going to index by status regularly, you might consider changing the structure of your object to support that directly. For instance, you might have a userCounts property that's an object with keys 0 through 3, which would let you index in directly:
// **IF** you change the structure so that `this` has a `userCounts`
// keyed by status:
for (const obj of this.allClients) {
const array = this.userCounts[obj.status];
if (array) { // Remove this for an error if status is an unexpected value
array.push(obj);
}
}
Live Example:
class Example {
constructor() {
this.allClients = [
{status: 0},
{status: 2},
{status: 2},
];
this.userCounts = {
0: [],
1: [],
2: [],
3: [],
};
}
method() {
for (const obj of this.allClients) {
const array = this.userCounts[obj.status];
if (array) {
array.push(obj);
}
}
}
}
const e = new Example();
e.method();
console.log(e);
elses…