I was wondering if there is a one liner is possible for something like
let updatedUser;
if (firstName) {
updatedUser = { ...userData,
Not really, however you could use a small helper:
const assignDefined = (target, props) =>
Object.entries(props).forEach(([k, v]) => v && (target[k] = v));
That allows you to write:
updateUser = assignDefined({...userData}, { firstName, lastName, password });
You can use
const updatedUser = Object.assign({},
userData,
firstName && {firstName},
lastName && {lastName},
password && {password}
);
or similar with object spread syntax:
const updatedUser = {
...userData,
...firstName && {firstName},
...lastName && {lastName},
...password && {password}
};
Falsy values will be ignored and not lead to the creation of any properties.