我正在尝试使用赋值和建议的对象扩展语法,我想知道是否有办法只分配一个条件?
例如,我目前有以下内容:
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,
},
有没有办法有条件地为对象分配属性?
由于
答案 0 :(得分:8)
你可以使用这种风格
const requestHeaders = {
...headers,
...(accessToken ? {
Authorization: `Bearer ${accessToken}`,
} : {}),
};
您可以使用所需的键或空对象传播对象。