Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add property to object only if value is defined

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 ?

like image 334
Frédéric Espiau Avatar asked Feb 07 '18 16:02

Frédéric Espiau


People also ask

How do you conditionally add property to an object?

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.

How do you assign a value to an object property?

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.


2 Answers

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.

like image 182
tmikeschu Avatar answered Oct 12 '22 05:10

tmikeschu


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

like image 36
Ravindra Thorat Avatar answered Oct 12 '22 03:10

Ravindra Thorat