0

This is an example of what I am trying to accomplish and as expected it is not working.

Is there something similar that would work?

var fieldsToCheck = ["a", "b", "c", "d", "e", "f"];

for (var i = 0; i < fieldsToCheck.length; i++){
    var field = fieldsToCheck[counter];
    if (!obj.field) {
         console.log('There is no field of: ' + field);
    }
 }

I originally did this using only if statements for every field, I am wondering whether or not there is a faster way to do this.

2
  • 1
    What is it you are trying to achieve? Commented May 6, 2015 at 21:08
  • obj.a equates to obj["a"] equates to prop = "a"; obj[prop] Commented May 6, 2015 at 21:10

1 Answer 1

2

You can't access the properties in that way. Since it's a variable, you have to use brackets instead of the dot notation:

var fieldsToCheck = ["a", "b", "c", "d", "e", "f"];

for (var i = 0; i < fieldsToCheck.length; i++){
    var field = fieldsToCheck[counter];
    if (!obj[field]) {
         console.log('There is no field of: ' + field);
    }
 }

When you use the dot notation e.g. obj.field, you're essentially asking if obj has a key field, rather than if obj has a key that is the value of variable field. For anything where you're accessing either unknown or string keys that contain non-variable valid characters like -, you'll have to use the bracket notation like obj[field] or obj["a"].

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

1 Comment

make sure you accept the answer when you're able to :-)

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.