Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add property to object when it's not null

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 would you add a property to an object class?

You can add a property to a previously defined object type by using the prototype property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object.

Can a property be added to an existing object in JavaScript?

You can add new properties to an existing object by simply giving it a value.

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.


You could use Object.assign in combination with the ternary operator:

let data = Object.assign({},
  first === null ? null : {first},
  ...
);

This works because Object.assign will skip over null parameters.

If you are sure that the property value is not going to be "falsy", then it would be bit shorter to write:

let data = Object.assign({},
  first && {first},
  ...
);

Assuming the object is going to be stringified at some point, since stringification ignores undefined values, you could also try

let data = {
  first: first === null ? undefined : first,
  ...
}

Depending on the JS version you are using, you can use the spread operator ...

const getData = data => ({
  ...data.first  && { 'Custom First Prop Name': data.first },
  ...data.second && { 'Custom Second Prop Name': data.second },
  ...data.third  && { third: data.third },
  ...data.fourth && { fourth: data.fourth },
});

Non-inline solution

If you don't need to add the value inline, it is pretty straightforward and clean to write your assignment like this.

const val1 = 1
const val2
const data = {}

val1 && (data.a = val1) // 1
val2 && (data.b = val2) // Not added
// data = { a : 1 }

NOTE: This will not work if the value is falsey