有条件地分配和设置js对象属性 [英] Assign, and set js object property conditionally

查看:44
本文介绍了有条件地分配和设置js对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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))
})

仅在 tipus ==='hianyos'时,如何才能将 rang 属性添加到对象?

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

推荐答案

更新后的答案:

这是您的操作方式:

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

console.log(item)

说明:

短路评估( true&& {} false&& {} )将返回 Object 布尔型假值.

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

在返回 Object 的情况下,其属性将散布并分配给父对象.

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

在返回 false 值的情况下,父对象不会受到污染,因为ES6将 false,undefined,null等值视为 {}.因此,扩展 ... {} 不会为父对象分配任何属性.有关此的更多详细信息,您可以在此处此处.

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.

这是您的操作方式:

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

说明:

如您所见,三元运算符总是返回对象.

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

如果条件为 true ,则返回 {范围:-1} ,否则返回空对象 {} .

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.

代码示例:(有时几行代码比数千个单词要好)

// 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.

这篇关于有条件地分配和设置js对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆