如何有条件地向javascript对象文字添加属性

Mur*_*rah 6 javascript object

我正在尝试执行以下操作以满足代码生成器的要求(Sencha Cmd是特定的).

这就是我需要做的事情.关键因素是函数体必须以对象文字的返回结束.由于构建器的限制,我无法返回变量.因此,如果参数'includeB'为true,如何在伪代码点处添加属性'b',但如果为false,则不添加属性AT ALL.即b == undefined或b == null是不允许的.

也许这是不可能的.

function create(includeB) {
        // Can have code here but the final thing MUST be a return of the literal.
        // ...
    return {
        a : 1
        // pseudo code:
        // if (includeB==true) then create a property called b 
        // and assign a value of 2 to it. 
        // Must be done right here within this object literal
    }
}

var obj = create(false);
// obj must have property 'a' ONLY

var obj = create(true);
// obj must have properties 'a' and 'b'
Run Code Online (Sandbox Code Playgroud)

感谢您的阅读和考虑,

穆雷

小智 10

如果可以使用ES6,请使用spread属性.

function create(includeB) {
    return {
        a : 1,
        ...(includeB ? { b: 2 } : {}),
    };
}
Run Code Online (Sandbox Code Playgroud)

  • 你甚至可以写`...(includeB && { b: 2 } )` (14认同)

zzz*_*Bov 5

您几乎已经展示了构造函数的用例,而不是使用对象文字:

function CustomObject(includeB) {
    this.a = 1;
    if (includeB) {
        this.b = 2;
    }
}

//has `a` only
var obj1 = new CustomObject(false);

//has `a` and `b`
var obj2 = new CustomObject(true);
Run Code Online (Sandbox Code Playgroud)

重新阅读您的问题后,您似乎在修改功能方面的访问权限受到限制。如果我正确理解你的问题,你只能更改脚本的有限部分:

function create(includeB) {
    // modifications may be done here

    // the rest may not change
    return {
        a : 1
    }
}

var obj = create(false);
// obj must have property 'a' ONLY

var obj = create(true);
// obj must have properties 'a' and 'b'
Run Code Online (Sandbox Code Playgroud)

如果是这种情况,那么您可以简单地跳过该函数的后面部分:

function create(includeB) {
    if (includeB) {
        return {
            a: 1,
            b: 2
        };
    }
    return {
        a: 1
    };
}
Run Code Online (Sandbox Code Playgroud)