Javascript array push only if value not null
With Spread operator for object literals (ECMAScript 2018) it looks super easy:
const myPush = (number, value, context, content) =>
array.push({
...{ number, value, context },
...content && { content }
});
If you are open to using ES2015, this can be done with Object.assign
:
array.push(
Object.assign(
{ number, value, context },
content ? { content } : null
)
);
If the objective isn't just to make code shorter, the most readable would be something like this, where you create the object, add the property if there is a value, and then push the object to the array.
push(number, value, context, content) {
var o = {
number : number,
value : value,
context : context
}
if (content !== null) o.content = content;
array.push(o);
);
Here's an ES6 way to construct the object directly inside Array.push
, and filter any that has null
as a value.
function push(...arg) {
array.push(['number','value','context','content'].reduce((a,b,i)=> {
if (arg[i] !== null) a[b]=arg[i]; return a;
}, {}))
}