Add property to object when it's not null

前端 未结 3 1005
我在风中等你
我在风中等你 2020-12-29 23:02

I\'m working on a small API and I want to update the data using HTTP PATCH REQUEST without using a bunch of if statements. I\'m trying to fill the outgoing data

3条回答
  •  灰色年华
    2020-12-29 23:56

    You could use Object.assign in combination with the ternary operator:

    let data = Object.assign({},
      first === null ? null : {first},
      ...
    );
    

    This works because Object.assign will skip over null parameters.

    If you are sure that the property value is not going to be "falsy", then it would be bit shorter to write:

    let data = Object.assign({},
      first && {first},
      ...
    );
    

    Assuming the object is going to be stringified at some point, since stringification ignores undefined values, you could also try

    let data = {
      first: first === null ? undefined : first,
      ...
    }
    

提交回复
热议问题