Update only non-empty fields | Object spread

后端 未结 2 1359
一生所求
一生所求 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 });
    

提交回复
热议问题