Sasi Dhivya Sasi Dhivya - 4 months ago 7
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

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

d=true;
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

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

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

In ES2015 you can do:

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