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.
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.
Share Improve this question edited Aug 5, 2016 at 10:57 JJJ 33.2k20 gold badges94 silver badges103 bronze badges asked Aug 5, 2016 at 10:37 Sasi DhivyaSasi Dhivya 5012 gold badges7 silver badges26 bronze badges 8-
There is a
)
after "body" that shouldn't be there – kapex Commented Aug 5, 2016 at 10:39 - i have removed that. its inserted wronly while updating query here – Sasi Dhivya Commented Aug 5, 2016 at 10:40
- you are inserting an object where a key: value is expected, you need a key for the object you are inserting – Poly Commented Aug 5, 2016 at 10:42
- I need something like this in args : Object {target: "div", status: "enabled", updated: "yes", type: "click", model: Object…} – Sasi Dhivya Commented Aug 5, 2016 at 10:50
- 2 My 2 cents : reducing number of lines won't always make your program run faster and/or increase maintainability. Also ternary operators are not as fast as strict parison : stackoverflow./questions/2586842/… . Ask yourself what does really matter ;) – mguimard Commented Aug 5, 2016 at 11:00
2 Answers
Reset to default 14Thats 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"};
You cannot use this operator in an object this way. Moreover, the data structure is incorrect. It would result in the following object :
{ { target:"whatever"} , status:"enabled", updated:"yes" };
Which is syntactically incorrect.
Consider writing something like this :
var args = {status:"enabled", updated:"yes" };
if(d){
args.target = 'div';
} else {
args.main = 'body';
}