Conditionally create json object

1.1k Views Asked by At

I'm using APISauce to create a post request to my server.

This works fine, and id, title and desc are variables that I pass in a function. return client.post("/workout", { userId: id, title: title, description: desc, });

description is optional, and I can't post it if the value is empty.

I can do it this way -

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

But this is a lot of duplicate, so I just want to check if there is a more efficient way of doing this? Can I check the description field within the JSON object?

2

There are 2 best solutions below

1
On BEST ANSWER

You can write

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

there's no need for the check. If desc is undefined the key description will be removed when stringified to JSON.

0
On

Following up with what Dave Newton suggested in the comments, it would work like the below

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

You're only creating the object once and if the property exists, you're setting it on the object.