0

我正在使用 APISauce 创建对我的服务器的发布请求。

这很好用,并且id, title and desc是我在函数中传递的变量。return client.post("/workout", { userId: id, title: title, description: desc, });

描述是可选的,如果值为空,我不能发布它。

我可以这样做-

if (desc){
return client.post("/workout", {
        userId: id,
        title: title,
        description: desc,
    });
}else
return client.post("/workout", {
        userId: id,
        title: title,
        
});

但这有很多重复,所以我只想检查是否有更有效的方法来做到这一点?我可以检查 JSON 对象中的描述字段吗?

4

2 回答 2

1

你可以写

client.post("/workout", {
    userId: id,
    title: title,
    description: desc,
});

不需要检查。如果desc未定义,description则在字符串化为 JSON 时将删除该键。

于 2021-03-09T18:45:54.240 回答
1

跟进 Dave Newton 在评论中的建议,它的工作原理如下

const body = {
  userId: id,
  title
};
if (desc) {
  body.description = desc;
}
client.post('/workout', body);

您只创建一次对象,如果属性存在,则将其设置在对象上。

于 2021-06-08T13:17:42.630 回答