1

Just tried to do something like this and it wont work, wondering if there is anyway?

var obj = {
    intiger:5,
    conditional:(something) ? "something" : "nothing",
    string:"nothing important"
};

This is breaking because of the presence of the : within the conditional. Anyway to do this without it breaking and keeping this format of obj.

I know that I can do.

obj.conditional = (something) ? "something" : "nothing";
1
  • My code was different then the example above and was missing a parentheses. Commented Nov 7, 2012 at 19:28

1 Answer 1

4

Use another set of parenthesis?

...
conditional:((something)?"something":"nothing"),
...

Just have to let the parser know which : to pay attention to and for which purpose.

var foo = {
    bar: (true ? "true" : "false")
};
console.log(foo.bar); // true

You can also use a function(){} if the decision needs to be made at the time of reference. e.g.

var foo = {
    bar:function(){
        return this.baz == 'Brad' ? 'Me' : 'Not Me';
    },
    baz: 'Brad'
};
console.log(foo.bar()); // 'Me'
foo.baz = 'Thomas'; console.log(foo.bar()); // 'Not Me'
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.