[英]how to conditionally create a member inside an object in javascript?
i was seeking for a solution like this in stackoverflow and in google but this is the idea 我正在stackoverflow和谷歌中寻找这样的解决方案,但这是个主意
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),
};
but i dont understand this... it doesnt work in nodejs i want to create an object a with many objects inside but if that objects are in the form send by the client 但是我不明白这一点...它在nodejs中不起作用我想创建一个内部有许多对象的对象,但是如果这些对象是客户端发送的形式
maybe what you want can be done using the array index notation? 也许可以使用数组索引符号完成所需的操作?
a= {};
if(bla) a.b = "go";
Try this: 尝试这个:
var a = {};
if(conditionB) {
a['b'] = 5;
}
or 要么
if(conditionB) {
a.b = 5;
}
This can be achieved in 2 ways. 这可以通过两种方式实现。
Either you use an if sentence for each conditional property as such: 您可以对每个条件属性使用if语句,如下所示:
var a = {};
if(conditionb){
a.b = 5;
}
Or if you don't want to create an if sentence for every property then you assign properties using the notation you presented in the question and then remove unnecessary ones in a loop: 或者,如果您不想为每个属性创建if语句,则可以使用问题中显示的符号来分配属性,然后在循环中删除不必要的属性:
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),
};
for(var i in a){
if(a[i] === undefined){
delete a[i];
}
}
You Can try this, 你可以试试看
var dog = d;
var myObject = {};
myObject['a']=(1<2)? 1 : 2;
myObject['b']=(1<2)? 1 : 2;
myObject['c']=(1<2)? 1 : 2;
myObject[dog]=(1<2)? 1 : 2;
Just in case you are creating the properties dynamically. 以防万一您正在动态创建属性。
You can do this with ES2018: 您可以使用ES2018执行此操作:
a = {
...(conditionB? { b : 5} : {}),
...(conditionC? { c : 5} : {}),
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.