Update only non-empty fields | Object spread

后端 未结 2 1357
一生所求
一生所求 2021-01-26 10:54

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

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


        
相关标签:
2条回答
  • 2021-01-26 11:10

    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 });
    
    0 讨论(0)
  • 2021-01-26 11:26

    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.

    0 讨论(0)
提交回复
热议问题