Assign, and set js object property conditionally

后端 未结 1 1971
说谎
说谎 2020-12-10 06:48

Here\'s my code:



        
相关标签:
1条回答
  • 2020-12-10 07:11

    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.

    0 讨论(0)
提交回复
热议问题