A way to prevent properties to be added to an object if they are null or undefined.

Rodrigo Carranza rodrigocarranza at outlook.com
Wed Nov 29 01:30:14 UTC 2017


A way to prevent properties to be added to an object if they are null or undefined.

Currently this can be accomplished in many ways:

With an if:
```js
function foo(couldBeNull){
let ret = {}
if(couldBeNull){
ret.couldBeNull = couldBeNull
}
return  ret
}
```

With ternary (kind of gross)
```js
function foo(couldBeNull){
let ret = {}
couldBeNull ? (ret.couldBeNull = couldBeNull) : null
return  ret
}
```

Also gross
```js
function foo(couldBeNull){
let ret = {}
couldBeNull && (ret.couldBeNull = couldBeNull)
return  ret
}
```

A bit hard to read:
```js
function foo(couldBeNull){
let ret = {
...({couldBeNull} : {})
}
return  ret
}
```

Requires importing a lib or writing the function by yourself. Also it has to iterate over all values
```js
function foo(couldBeNull){
let ret = {
couldBeNull
}
ret = removeEmptyValues(ret) // imported from some library
return  ret
}
```

Wouldn't it be better something like this?:

```js
function foo(couldBeNull){
let ret = {
couldBeNull?
}
return  ret
}
```

Or if you want to set other property name

```js
function foo(couldBeNull){
let ret = {
bar ?:  couldBeNull // bar is not added if couldBeNull is null or undefined
}
return  ret
}
```

[https://ipmcdn.avast.com/images/icons/icon-envelope-tick-round-orange-animated-no-repeat-v1.gif]<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=emailclient>      Libre de virus. www.avast.com<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=emailclient>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20171129/dc7a3ad4/attachment.html>


More information about the es-discuss mailing list