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.';
});