我想创建一个有条件添加成员的对象.简单的方法是:
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) 是否有一些基于条件设置属性的语法?
data: {
userId: 7,
actionId: 36,
express: (myCondition ? true : null) // does not work
}
Run Code Online (Sandbox Code Playgroud)
我想要express设置为一个值或根本不设置(即,应该没有命名的键express),并且在定义之后没有额外的语句.我知道我可以使用它作为布尔值,但接收方正在使用isset()支票,我想知道我是否可以避免修改它.
编辑:似乎没有直接解决问题的方法如上所述.以下是密切的建议:
JSON.stringify(Chris Kessel,dystroy):
var json = JSON.stringify( {
data: {
userId: 7,
actionId: 36,
express: (myCondition ? true : null)
}
});
Run Code Online (Sandbox Code Playgroud)
一个匿名函数(Paulpro):
var data = new function(){
this.userId = 7;
this.actionId = 36;
myCondition && (this.express = true);
};
Run Code Online (Sandbox Code Playgroud)
额外声明(x4rf41):
data: {
userId: 7,
actionId: 36
}
if(myCondition) data["express"] = …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