Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

javascript - Conditionally set an object property

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 express to 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.


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

JSON.stringify (Chris Kessel, dystroy):

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

An anonymous function (Paulpro):

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

An extra statement (x4rf41):

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

Eval (a former colleague of mine):

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 })
);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...