0

Suppose below I wanted to change 'valid' for 'a','b' and 'c' equal to true. For the object foo.

var foo = {
    a: {
        valid: false,
        required: true
    },
    b: {
        valid: false,
        required: true
    },
    c: {
        valid: false,
        required: true
    }
};

for (var key in foo) {
    var obj = foo[key];
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            //how can I assign valid to true here?
        };

    }
3
  • obj[prop].valid = true ? You already know how to access object properties in a loop and how to perform an assignment, so I don't get what the issue is. Commented Jun 18, 2015 at 23:50
  • @squint That doesn't work. jsfiddle.net/9ju25fff Commented Jun 18, 2015 at 23:56
  • @BDillan: He means key, not prop, in the outer loop. Commented Jun 19, 2015 at 0:10

2 Answers 2

2

You're making this more complicated than it needs to be.

Just do this:

for( var key in foo ) {
    foo[key].valid = true;
}

Or, if you're concerned that some code in your page may have extended Object.prototype with an enumerable property, you can do this instead:

for( var key in foo ) {
    if( foo.hasOwnProperty(key) ) {
        foo[key].valid = true;
    }
}

But nobody should ever extend Object.prototype with an enumerable property. That breaks all kinds of code. It's very unlikely that this would be an issue you'd need to worry about.

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

Comments

0

Like this: FIDDLE

for (var key in foo) {
    var obj = foo[key];
    for (var prop in obj) {
        if (obj.hasOwnProperty("valid")) { //checks if "valid" exists
            if (!obj.valid) { //if valid=false change to true, else ignore
                obj.valid = true;
            };
        }

    }
}
console.log(foo);

1 Comment

You're not using prop

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.