I have following code snippet. I need to add this to a loop. What is the best way that I can follow.
A js object named Data is passed to the following JavaScript method and I need to check whether certain key are assigned the value "". Currently I'm using set of 'if' statement as below but I would like to acheive this using a loop.
privateMethods.generatePasswordDataPayload = function (Data) {
if (Data["passwordLength"] == "") {
Data["passwordLength"] = null;
}
if (Data["passwordComplexCharactors"] == "") {
Data["passwordComplexCharactors"] = null;
}
if (Data["passwordExpTime"] == "") {
Data["passwordExpTime"] = null;
}
if (Data["passwordHistory"] == "") {
Data["passwordHistory"] = null;
}
if (Data["passwordAttempts"] == "") {
Data["passwordAttempts"] = null;
}
}
Can I use any regex patterns and do something similar as below (pseudo code)
var i = 0;
while (Data.length >= i){
if ((Data["password(regex pattern check)") == ""){
(Data["password(regex pattern check)") == null;
}
i++;
}
Please note that I'm using JavaScript here.
If you want to list each property and set a value you can do something like this
for(objectName in Data) {
if(Data[objectName]=="") {
Data[objectName] == null;
}
}
String.prototype.indexOf will return the index of the first occurence of the string passed as parameter. So to get all the keys that start with "password"
, you have to check if indexOf("password")
return 0
or not (if it returned 0
then the key start with password
, otherwise it doesn't).
privateMethods.generatePasswordDataPayload = function (Data) {
for(var key in Data) { // for each key in Data
if(key.indexOf("password") == 0) { // if the key starts with "password"
Data[key] = null; // set the value to null
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.