Sasi Dhivya Sasi Dhivya - 1 year ago 99
Javascript Question

Unable to use ternary operator within object data

I am using JavaScript and jQuery for my web application. In one case I have used the ternary operator in order to optimize the code while assigning object values.

I have manually set the

value to true for testing. But this value will vary based on customer given data in my application.

var args = { d ? { target:"div"} : {main:"body"}, status:"enabled", updated:"yes" };

But this does not work and throws script error. Can you suggest how to update object data in optimized way.

Answer Source

Thats incorrect JavaScript syntax, You cant dynamicaly define properies on object this way. You can do this:

var args = {status:"enabled", updated:"yes"};
d ? ( = "div") : (args.main = "body");

In ES2015 you can do:

var args = {[d ? "target" : "main"]: d ? "div" : "body", status:"enabled", updated:"yes"};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download