Update only non-empty fields | Object spread

2020-05-02 10:26发布

问题:

I was wondering if there is a one liner is possible for something like

        let updatedUser;
        if (firstName) {
            updatedUser = { ...userData, firstName };
        }
        if (lastName) {
            updatedUser = { ...userData, lastName };
        }
        if (password) {
            updatedUser = { ...userData, password };
        }

I'm just checking for empty firstName, lastName and so forth. What if I have several fields like this?

So I don't want to update any of my fields with empty values if I write

updatedUser = { ...userData, firstName, lastName, password  };

Any possible alternative that exists that can tell object spread or anything else to not update if my field is empty?

回答1:

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.



回答2:

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 });