Reputation: 2038
I would like to change all property values of a JavaScript object to a certain value (false in this case). I know how to do this by changing all of them individually (Example A) or with a loop (Example B). I was wondering if there are any other built in methods to do this, and what is the recommended way (mainly in terms of speed or if there are any other side effects)?
Pseudocode:
// Example object
Settings = function() {
this.A = false;
this.B = false;
this.C = false;
// more settings...
}
// Example A - currently working
updateSettingsExampleA = function(settings) {
// Settings' properties may not be be false when called
settings.A = false;
settings.B = false;
settings.C = false;
while (!(settings.A && settings.B && settings.C) && endingCondition) {
// code for altering settings
}
}
// Example B - currently working
updateSettingsExampleB = function(settings) {
// Settings' properties may not be be false when called
for (var property in settings) {
settings[property] = false;
}
while (!(settings.A && settings.B && settings.C) && endingCondition) {
// code for altering settings
}
}
// possible other built in method
updateSettingsGoal = function() {
this.* = false; // <-- statement to change all values to false
while (!(this.A && this.B && this.C) && endingCondition) {
// code for altering settings
}
}
Upvotes: 0
Views: 58
Reputation: 664297
No, there is no such built-in method. If you want to "change all property values to false", then use a loop to do so. Your Example B is totally fine.
I wouldn't recommend unrolling the loop (Example A) except it's not "all properties" or you require absolute maximum speed for this snippet. But that's a micro-optimisation, it doesn't make your code better.
Upvotes: 2