0

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.';
});
8
  • Possible duplicate of Dynamically access object property using variable Commented Sep 18, 2019 at 14:45
  • What is this in your JS example? i.e. is it an array, an object, or something else? Commented Sep 18, 2019 at 14:45
  • 3
    this.[field] -> this[field] although you also need to make sure the correct context is preserved Commented Sep 18, 2019 at 14:45
  • 1
    Also, those aren't variable variables - in PHP a variable variable is $key = "dynamic"; $$key = "dynamically set"; where $$key would resolve to the variable $dynamic Commented Sep 18, 2019 at 14:48
  • @Taplar variable variables are a thing in PHP. Look at my other comment. Basically, you use the value of one variable to access another by name. It's...very unwieldy. Commented Sep 18, 2019 at 14:49

1 Answer 1

1

U can do that almost same way as in php:

class Person {

  constructor(name, surname, email) {
    this.name = name;
    this.surname = surname;
    this.email = email;
    this.errors = {}
  }
  
  validate () {
    ['name', 'surname', 'email'].forEach((field) => {
      if (!this[field])
          this.errors[field] = field + ' is required.';
    });
  }
  
  getErrors() {
    return this.errors;
  }
}

let s = new Person('john','doe');
s.validate();
console.log(s.getErrors());

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.