gpt4 book ai didi

javascript - ES6 Javascript 速记仅在属性为真时才创建属性

转载 作者:搜寻专家 更新时间:2023-11-01 05:19:40 25 4
gpt4 key购买 nike

假设我有

const {status} = req.body;

只有当状态具有真实值(nullundefined 时,我才想在我的查询对象中包含 status空字符串),

目前我正在做这件事,

const query = {
otherCondition: 1,
};

if (status) {
query.status = status;
}

有什么方法可以避免使用 if 子句使用 ES6 对象速记?

如果我使用,

const query = {
otherCondition: 1,
status,
}

当状态为undefined时,生成

{
otherCondition: 1,
status: "undefined",
}

最佳答案

您可以使用 object spreadshort circuit evaluation :

...status && { status }

如果 status 是一个假值,计算的表达式将不会“返回”对象,spread 将忽略它。如果它是真实值,短路将“返回”{status} 对象,并且传播将以正常方式工作:

虚假

const {status} = {};

const query = {
otherCondition: 1,
...status && { status }
};

console.log(query);

真实

const {status} = { status: 5 };

const query = {
otherCondition: 1,
...status && { status }
};

console.log(query);

关于javascript - ES6 Javascript 速记仅在属性为真时才创建属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51401065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com