I see 2-3 options depending on your excludeObjNullValue function:
You can either break that expression up in to a couple of statements, or
Or use property spread notation and the conditional operator, or
If excludeObjNullValue does what the name suggests, you can use a conditional without spread notation and rely on excludeObjNullValue to exclude it
Option 3 may well be your best bet, but I'll give them in order:
Option 1: The multi-statement way:
const createUser = (payload) => {
const options = {
username: payload.username,
email: payload.email,
password: payload.password,
first_name: payload.firstName,
last_name: payload.lastName,
role: payload.role,
district_id: payload.districtId,
};
if (role !== 'p_admin') {
options.school_ids = payload.schoolIds;
}
return request.postJSON('/register', excludeObjNullValue(options));
};
Option 2: Property spread and the conditional operator
Property spread is a Stage 3 proposal but support for it is already shipping in Chrome and Firefox, and if you're transpiling you can tell your transpiler to support it. That would look like this:
const createUser = (payload) => request.postJSON(
'/register',
excludeObjNullValue({
username: payload.username,
email: payload.email,
password: payload.password,
first_name: payload.firstName,
last_name: payload.lastName,
role: payload.role,
district_id: payload.districtId,
{...(role !== 'p_admin' ? {school_ids: payload.schoolIds} : {}}
}
})
);
Whether it's a good idea even if supported is your call. :-) It does briefly create an extra object and iterator.
Option 3: Rely on excludeObjNullValue to exclude properties with null values:
If it really does what the name suggests, then it will remove school_ids if we give the value null to it. So:
const createUser = (payload) => request.postJSON(
'/register',
excludeObjNullValue({
username: payload.username,
email: payload.email,
password: payload.password,
first_name: payload.firstName,
last_name: payload.lastName,
role: payload.role,
district_id: payload.districtId,
school_ids: role !== 'p_admin' ? payload.schoolIds : null
}
})
);