Basically I wonder if I could avoid adding a property into an object if a variable is false but from inside the object. So let's say I have this object:
var obj = { foo: 'bar', bar: 'foo' };
Now I want to rewrite the same object but I only want to add the second property if a new variable, which is a boolean, is true. The problem is how could I do this for example with a ternary operator like this:
var add = false;
var obj = {
foo: 'bar',
(add ? bar: 'foo': null)
};
What I want to avoid is to have this:
...
bar: ( add ? 'foo' : undefined )
Because I don't want to have the bar index in case add == false. Also the assignament must be inside to object ( that's the question about, if it's posible ) because something like this is not what I'm looking for:
...
if (!add) delete obj.bar; // This would be after the creation of the whole object
Work arounds
Obviously this can be achieved in many ways, but I haven't found any that is done inside the object itself. I could use a ternary operator and having two objects like this:
var obj = add ? {
foo: 'bar',
bar: 'foo'
} : { foo: 'bar' };
But this would lead to having duplicated code ( when the object has more properties ).
Edit I'd say that my question is slightly different from the duplicates since my question refers to do it inside the object not after its declaration nor anything that isn't between var obj = { ... }
There is an accepted answer but I would love if someone knows any other way of doing it without the use of spread operator. Thank you all