Is there a better way to add a property to an object only if the value is defined :
const destination = {};
const value = getValue();
if (_(value).isObject()) { // In this case, I only want an object
destination.value = value;
}
In this case, the destination.value
property exists only if value
has a value. Is there a better way to do this ?
To conditionally add a property to an object, we can make use of the && operator. In the example above, in the first property definition on obj , the first expression ( trueCondition ) is true/truthy, so the second expression is returned, and then spread into the object.
assign() which is used to copy the values and properties from one or more source objects to a target object. It invokes getters and setters since it uses both [[Get]] on the source and [[Set]] on the target. It returns the target object which has properties and values copied from the target object.
With ES6, I like to do conditional spreading:
const value = getValue()
const destination = {
...(value ? { value } : {})
}
And you can do whatever boolean check you need in the ternary. In your case, checking to see if value
is an object.
Update
Here is a better way,
const destination = {};
const value = getValue();
destination = {
...destination,
...value && ({value})
}
Here the assumption is you want to make a key with the name value
itself.
Another approach
just do like this,
const destination = {};
const value = getValue();
value && (destination.value = value); // here is the one liner way
This will make sure that the value attribute is getting create only if value is defined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With