我想创建一个有条件添加成员的对象.简单的方法是:
var a = {};
if (someCondition)
a.b = 5;
Run Code Online (Sandbox Code Playgroud)
现在,我想写一个更惯用的代码.我在尝试:
a = {
b: (someCondition? 5 : undefined)
};
Run Code Online (Sandbox Code Playgroud)
但现在,b是a其价值的成员undefined.这不是理想的结果.
有方便的解决方案吗?
更新
我寻求一个可以处理几个成员的一般情况的解决方案.
a = {
b: (conditionB? 5 : undefined),
c: (conditionC? 5 : undefined),
d: (conditionD? 5 : undefined),
e: (conditionE? 5 : undefined),
f: (conditionF? 5 : undefined),
g: (conditionG? 5 : undefined),
};
Run Code Online (Sandbox Code Playgroud) 我正在尝试执行以下操作以满足代码生成器的要求(Sencha Cmd是特定的).
这就是我需要做的事情.关键因素是函数体必须以对象文字的返回结束.由于构建器的限制,我无法返回变量.因此,如果参数'includeB'为true,如何在伪代码点处添加属性'b',但如果为false,则不添加属性AT ALL.即b == undefined或b == null是不允许的.
也许这是不可能的.
function create(includeB) {
// Can have code here but the final thing MUST be a return of the literal.
// ...
return {
a : 1
// pseudo code:
// if (includeB==true) then create a property called b
// and assign a value of 2 to it.
// Must be done right here within this object literal
}
}
var obj = create(false);
// obj must have property 'a' ONLY
var …Run Code Online (Sandbox Code Playgroud) 这是我的代码:
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))
})Run Code Online (Sandbox Code Playgroud)
我该怎么做才能将rang属性添加到对象中tipus === 'hianyos'?
我想有条件地在对象上创建属性。这个想法是确保该属性在没有值的情况下不存在(因此不仅仅是 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