Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

Better solution for forEach and if ? map, filter Javascript

I really need bettter solution for this logic:

    this.allClients.forEach(obj => {
     if(obj.status === 2) {
       this.numOfWaitingUsers.push(obj) 
     }
     if(obj.status === 1) {
      this.numOfInactiveUsers.push(obj) 
    }
    if(obj.status === 0) {
      this.numOfActiveUsers.push(obj) 
    }
    if(obj.status === 3) {
      this.numOfAClosedUsers.push(obj) 
    }
    })

This is work perfect but i need better soluiton. i know to can be better with less code.

question from:https://stackoverflow.com/questions/65849795/better-solution-for-foreach-and-if-map-filter-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...