Conditionally set an object property

后端 未结 6 1959
太阳男子
太阳男子 2020-12-04 17:37

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

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


        
相关标签:
6条回答
  • 2020-12-04 18:06

    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 data object is the exact same, except it's constructor will be the anonymous function instead of window.Object.

    0 讨论(0)
  • 2020-12-04 18:08

    You could do something like this:

    var json = JSON.stringify( {
        data: {
            userId: 7,
            actionId: 36,
            express: (myCondition ? true : null)
        }
    });
    
    0 讨论(0)
  • 2020-12-04 18:16

    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} : {})
    }
    
    0 讨论(0)
  • 2020-12-04 18:20

    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.

    0 讨论(0)
  • 2020-12-04 18:22

    Do it like this :

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

    A property whose value is undefined isn't written when you stringify the object to JSON.


    EDIT : It appears from the comments that there is no JSON involved in fact. OP is using $.ajax so $.param is 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.

    0 讨论(0)
  • 2020-12-04 18:25

    first of all, thats javascript, not JSON.

    the solution:

    data: {
        userId: 7,
        actionId: 36
    }
    if(myCondition) data["express"] = true;
    
    0 讨论(0)
提交回复
热议问题