mbe*_*son 0 javascript node.js typescript
我想有条件地在对象上创建属性。这个想法是确保该属性在没有值的情况下不存在(因此不仅仅是 null)。
我现在正在做什么:
// comes from users
req.query = {
foo: true
}
// my object which will contains allowed properties IF EXISTS
const where = {}
if (req.query.foo) {
where.foo = req.query.foo
}
if (req.query.bar) {
where.bar = req.query.bar
}
console.log(where)Run Code Online (Sandbox Code Playgroud)
对每个不同的属性重复这个真的很无聊......
有没有一种方法可以在一行中完成?
编辑:
我不想获取所有属性req.query
Nik*_*zur 12
如果值存在(或任何其他条件),则创建对象属性 obj.foo
&&如果满足第一个布尔条件,运算符返回第二个元素
es6 扩展运算...符执行其操作)
const value = 'bar'
const empty = undefined
const obj = {
...value && { foo: value }, // read ...(value && { foo: value }) parenthesis are not necessary
...empty && { empty },
...(100 > 0) && { condition: 'true' },
...(100 < 0) && { condition: 'false' },
}
console.log(obj)Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9603 次 |
| 最近记录: |