简体   繁体   English

仅更新非空字段| 对象传播

[英]Update only non-empty fields | Object spread

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. 我只是在检查空的firstName,lastName等。 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? 如果我的字段为空,是否存在可以告诉对象传播或其他任何内容不更新的可能替代方案?

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. 虚假值将被忽略,不会导致任何属性的创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM