Home > Back-end >  How to trigger condition to only the listed names
How to trigger condition to only the listed names

Time:10-23

I currently created this condition that only works for the listed userName from the data.uniqueId. Without the condition, it works to all names from the data.uniqueId. My purpose is so I could trigger the addContent to some names of my choice only, those that I will put the list.

let userName = data.uniqueId;

if(userName == "name1"){
        addContent(
            `<img src="${userAvatar}" style="width:25px;height:25px;border-radius: 50%;"/>&nbsp;<span >Host</span>
            <span style="font-weight: bold;">${userName}</span>: ${message}`
            );
}

The code I have now is working but only for name1, I don't know how to do the code if I want to have more than 1 userName in the list.

Could anyone help me with this? I would appreciate it if you could come up with a way that's easier for me to add more names to the list in the future, maybe a different .js file just for the name list and then call to a different .js file where I currently have the code above.

Otherwise, any method that works should be fine enough. Thank you in advance!

CodePudding user response:

create an array with the possible names

const names = ["name1", "name2", ...]

and then in the condition do a

if(names.includes(userName)){...

CodePudding user response:

you could use an array (a list of elements) which has a method called includes(element) which will return true if the element is present on the list. Something like this:


let userNames = ["name1","name2","name3"];

if(userNames.include("name1")){ // will return true, thus entering the if
        addContent(
            `<img src="${userAvatar}" style="width:25px;height:25px;border-radius: 50%;"/>&nbsp;<span >Host</span>
            <span style="font-weight: bold;">${userName}</span>: ${message}`
            );
}

more information about includes here: https://www.w3schools.com/jsref/jsref_includes_array.asp

CodePudding user response:

I am not completely clear on what you want but this might be helpful.

Declare or build an array of names:

const names = ["Alice", "Bob", "Charles"];

if the name you want to test is:

const userName = "Bob";

You can then do an if statement like this:

if (names.includes(userName)) {
   // do whatever 
}

Note that this test is case sensitive.

CodePudding user response:

I assume that data is an array. then you can use for each to loop through all the elements in it

let userName = data.uniqueId;

data.forEach(user => {

    if(user.uniqueId == "name1"){
        addContent(
            `<img src="${userAvatar}" style="width:25px;height:25px;border-radius: 50%;"/>&nbsp;<span >Host</span>
            <span style="font-weight: bold;">${userName}</span>: ${message}`
            );
    }
    
});
  • Related