【问题标题】:Conditionally create json object有条件地创建 json 对象
【发布时间】:2023-04-01 04:01:01
【问题描述】:

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

这很好用,id, title and desc 是我在函数中传递的变量。 return client.post("/workout", { 用户ID:身份证, 标题:标题, 描述:描述, });

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

我可以这样做-

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

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

【问题讨论】:

  • 如果您使用的任何东西都不会自动过滤掉未定义的值,只需创建基础对象,添加描述(如果存在),并使用创建的对象进行单个 post 调用。这里有重复只是因为您没有将参数创建与帖子分开。
  • 我确实可以这样做,但它仍然是重复的,我将重新创建一个对象,一个有描述,另一个没有。
  • 不,你会创建一个对象,并有条件地向它添加一个属性。

标签: javascript reactjs react-native apisauce


【解决方案1】:

你可以写

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

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

【讨论】:

  • 我刚试过这个,我仍然得到 undefined const description = desc ?描述:未定义; console.log("训练后" + 描述); return client.post("/workout", { userId: id, title: title, description: description, });即使描述未定义,我仍然收到错误,因为描述不应该为空。
【解决方案2】:

按照 Dave Newton 在 cmets 中的建议,它会像下面这样工作

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

你只创建了一次对象,如果属性存在,你就在对象上设置它。

【讨论】:

    猜你喜欢
    • 2014-05-15
    • 2015-09-30
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 2019-01-26
    • 1970-01-01
    相关资源
    最近更新 更多