In PHP it is common to use variable variables, e.g.
foreach(['key1', 'key2', 'key3'] as $key) {
if (!$object->$key)
$object->$key = 'add some values';
}
i wonder how can one do that in javascript?
Practical use case:
we have multiple required input fields (e.g.: name, surname, email) in form with no-validate, values are automatically pushed to this instance (meaning we can access values with this.name, this.surname, etc). We need to ensure these fields are filled.
One could write something like:
if (!this.name)
this.errors['name'] = 'This field is required.';
if (!this.surname)
this.errors['surname'] = 'This field is required.';
if (!this.email)
this.errors['email'] = 'This field is required.';
I am trying to come up with something more compact and accurate like:
['name', 'surname', 'email'].forEach(function (field) {
if (!this.[field])
this.errors[field] = 'This field is required.';
});
thisin your JS example? i.e. is it an array, an object, or something else?this.[field]->this[field]although you also need to make sure the correct context is preserved$key = "dynamic"; $$key = "dynamically set";where$$keywould resolve to the variable$dynamic