条件赋值和 ECMAScript 提议的对象扩展语法

Conditional assignment and ECMAScript proposed object spread syntax

我正在研究赋值和提议的对象传播语法,我想知道是否有一种方法可以仅根据条件赋值?

比如我目前有以下:

const requestHeaders = { ...headers };

if (accessToken) {
    requestHeaders.Authorization = `Bearer ${accessToken}`;
}

const h = {
    Accept: 'application/json',
    ...requestHeaders,
},

我想用这样的东西来简化它:

const requestHeaders = {
    ...headers, {
        Authorization: accessToken ? `Bearer ${accessToken}` : void 0, // I don't want Authorization to appear in the object if it's null or undefined, but this doesn't work
    }
};

const h = {
    Accept: 'application/json',
    ...requestHeaders,
},

有什么方法可以有条件地将属性分配给对象吗?

谢谢

你可以使用这种风格

const requestHeaders = {
    ...headers,
    ...(accessToken ? {
        Authorization: `Bearer ${accessToken}`,
    } : {}),
};

您可以在其中传播带有所需键的对象或空对象。