Setting attributeTwo using an if statement. What is the correct way to do this?
var testBoolean = true;
var object = {
attributeOne: "attributeOne",
attributeTwo: if (testBoolean) { "attributeTwo" } else { "attributeTwoToo" },
}
Setting attributeTwo using an if statement. What is the correct way to do this?
var testBoolean = true;
var object = {
attributeOne: "attributeOne",
attributeTwo: if (testBoolean) { "attributeTwo" } else { "attributeTwoToo" },
}
No, however you can use the ternary operator:
var testBoolean = true;
var object = {
attributeOne: "attributeOne",
attributeTwo: testBoolean ? "attributeTwo" : "attributeTwoToo"
}
You can use an if statement, if it is within a immediately invoked function.
var x = {
y: (function(){
if (true) return 'somevalue';
}())
};
You can't use an if statement directly, but you can use ternary operator (aka conditional operator) which behaves the way you want. Here is how it would look:
var testBoolean = true;
var object = {
attributeOne: "attributeOne",
attributeTwo: testBoolean ? "attributeTwo" : "attributeTwoToo"
}
you can also do by this method
var testBoolean = true;
var object = {
attributeOne: "attributeOne"
}
1
if(testBoolean){
object.attributeTwo = "attributeTwo"
}else{
object.attributeTwo = "attributeTwoToo"
}
2
object.attributeTwo = testBoolean ? "attributeTwo" : "attributeTwoToo"
you can put a conditional statement like this way, where conditional statement also works for object's key also.
let inbox = true;
let assign = {...(inbox ? {assign_to: 2} : {})};
console.log("assign", assign);
inbox = false;
assign = {...(inbox ? {assign_to: 2} : {})};
console.log("assign", assign);
I know this question is really old but i haven't seen anyone give this answer so i'll just drop this here, you can actually pass a function inside the property of your object like this:
var testBoolean = true;
const genericFunc = (testBoolean) => {
if(testBoolean !== true){
return 'False'
}else {
return 'True'
}
}
var object = {
attributeOne: "attributeOne",
attributeTwo: genericFunc(testBoolean),
}
console.log('Object',object)
As long as the function you pass actually has a return statement, it'll work!
Indeed you can but why don't you do the conditional statement before assigning it to object attribute. The code would be nicer.