13

Here's my code:

app.post('/ujfeladat', (req, res) => {
    const {nev, tipus, szid} = req.body;
    const hianyos = () => {
        if(tipus === 'hianyos'){
            return {rang: -1}
        }
        return
    }
    db('fl').insert({
        nev: nev,
        tipus: tipus,
        szid: szid,
        hianyos() //returns an error
    }).returning('*')
    .then(data => res.json(data))
    .catch(err => console.log(err))
})

How can i do that to add the rang property to the object only if the tipus === 'hianyos'?

1
  • Are you fine if rang exists with undefined stored or you don't want anything related to rang Commented May 16, 2018 at 9:32

1 Answer 1

56

Updated answer:

Here's how you can do it:

// Will result in { foo: 'foo', bar: 'bar'}
const item = {
  foo: 'foo',
  ... true && { bar: 'bar' },
  ... false && { falsy: 'falsy' },
}

console.log(item)

Explanations:

Short-circuit evaluation (true && {}, false && {}) would return an Object or a Boolean false value.

In the case an Object is returned, its properties get spread and assigned to the parent object.

In the case false value is returned, the parent object isn't polluted, because ES6 treats false, undefined, null and etc values as {}. Therefore spreading ...{} won't assign any properties to the parent object. More details about this, you can find here.


Original answer:

Here's how you can do it:

db('fl').insert({
  nev: nev,
  tipus: tipus,
  szid: szid,
  ...tipus === 'hianyos' ? { rang: -1 } : {}
})

Explanations:

As you can see the ternary operator always returns an object.

If the condition is true, then it returns { rang: -1 }, otherwise an empty object {}.

After that we spread out ... the resulted object (from the ternary operation) and the object's properties are assigned to the parent object.

If there aren't any properties, then nothing will be assigned, which is our goal.

Code example: (sometimes few lines of code better than a thousands of words)

// Will result in { foo: 'foo', bar: 'bar'}
const item = {
  foo: 'foo',
  ... true ? { bar: 'bar' } : {},
  ... false ? { falsy: 'falsy' } : {},
}

console.log(item)

In other answer I explained the same idea, but for arrays. You can check it too here.

Sign up to request clarification or add additional context in comments.

6 Comments

wow!! 2 years ago, you wouldn't even recognize that as javascript :p
Thank you very much! It works! But can you please tell the name of this syntax?
@GeraszHorváth you can check the details. Feel free to ask :)
Only the spread was the unknown element, but i did read about it, it's very useful, but i don't really understand it yet because of the many possible use form of it. Obejcts, arrays, functions, and all have different meanings. Thanks for the answer again, it helped me a lot!
Hmm. @carinlynchin thank you for the feedback! Maybe you have to consider checking babeljs.io/docs/en/babel-plugin-proposal-object-rest-spread
|