javascript 有条件地设置对象属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18019854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:29:29  来源:igfitidea点击:

Conditionally set an object property

javascript

提问by mcmlxxxvi

Is there some syntax for setting properties based on a condition?

是否有一些基于条件设置属性的语法?

data: {
    userId: 7,
    actionId: 36,
    express: (myCondition ? true : null) // does not work
}

I want expressto be either set to a value or not set at all (i.e., there should be no key named express), and without extra statements after the definition. I know I can use it as a boolean, but the receiving side is using an isset()check and I'm wondering if I can avoid modifying it.

我想express被设置为一个值或根本不设置(即,不应该有名为 的键express),并且在定义之后没有额外的语句。我知道我可以将它用作布尔值,但是接收方正在使用isset()支票,我想知道是否可以避免修改它。



Edit: Seems there is no direct solution to the problem as stated. Here are the close suggestions:

编辑:似乎没有直接解决上述问题的方法。以下是接近的建议:

JSON.stringify(Chris Kessel, dystroy):

JSON.stringify(Chris Kessel,dystroy):

var json = JSON.stringify( {
    data: {
        userId: 7,
        actionId: 36,
        express: (myCondition ? true : null)
    }
});

An anonymous function(Paulpro):

匿名函数(Paulpro):

var data = new function(){
    this.userId = 7;
    this.actionId = 36;
    myCondition && (this.express = true);
};

An extra statement(x4rf41):

额外的语句(x4rf41):

data: {
    userId: 7,
    actionId: 36
}
if(myCondition) data["express"] = true;

Eval(a former colleague of mine):

Eval(我的前同事):

eval("data = {userId: 7, actionId: 36 " + (myCondition ? ", express: true}" : "}"))

Conditional definition(don't really know how to label this one):

条件定义(真的不知道如何标记这个):

data = (
    (myCondition && { userId: 7, actionId: 36, express: true }) ||
    (!myCondition && { userId: 7, actionId: 36 })
);

采纳答案by Denys Séguret

Do it like this :

像这样做 :

data: {
    userId: 7,
    actionId: 36,
    express: (myCondition ? true : undefined)
}

A property whose value is undefinedisn't written when you stringifythe object to JSON.

将对象字符串化为JSONundefined时,不会写入值未写入的属性。



EDIT : It appears from the comments that there is no JSON involved in fact. OP is using $.ajaxso $.paramis probably used. $.param, unfortunately, does create an entry for properties whose value is undefined. So there's probably no solution without any supplementary line of code.

编辑:从评论看来,实际上没有涉及 JSON。OP 正在使用$.ajax所以$.param可能使用。$.param不幸的是,它确实为值为 的属性创建了一个条目undefined。因此,如果没有任何补充代码行,可能就没有解决方案。

回答by ericsoco

Use the spread operator.

使用扩展运算符

data: {
    userId: 7,
    actionId: 36,
    ...myCondition && {express: true}
}

Note that if you're using Flow, that syntax might generate type check errors. You can write the above more explicitly, and less succinctly, as:

请注意,如果您使用Flow,则该语法可能会生成类型检查错误。您可以更明确、更简洁地编写上述内容,如下所示:

data: {
    userId: 7,
    actionId: 36,
    ...(myCondition ? {express: true} : {})
}

回答by Paul

You can do it if you define your object using an anonymous function instead of object literal notation:

如果您使用匿名函数而不是对象文字表示法定义对象,则可以这样做:

var data = new function(){
    this.userId = 7;
    this.actionId = 36;
    myCondition && (this.express = true);
};

The resulting dataobject is the exact same, except it's constructorwill be the anonymous function instead of window.Object.

结果data对象完全相同,除了它将constructor是匿名函数而不是window.Object.

回答by Chris Kessel

You could do something like this:

你可以这样做:

var json = JSON.stringify( {
    data: {
        userId: 7,
        actionId: 36,
        express: (myCondition ? true : null)
    }
});

回答by x4rf41

first of all, thats javascript, not JSON.

首先,那是 javascript,而不是 JSON。

the solution:

解决方案:

data: {
    userId: 7,
    actionId: 36
}
if(myCondition) data["express"] = true;

回答by Imad El Hitti

A bit old but there is a good solution as well you can do :

有点旧,但也有一个很好的解决方案,您可以这样做:

data: {
    userId: 7,
    actionId: 36
}

Object.assign(data, !myCondition && { express: yourValue });

Thus it will assign your express property with the value you need if your condition is false.

因此,如果您的条件为假,它将为您的 express 属性分配您需要的值。