Add property to object when it's not null

前端 未结 3 1010
我在风中等你
我在风中等你 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:47

    Depending on the JS version you are using, you can use the spread operator ...

    const getData = data => ({
      ...data.first  && { 'Custom First Prop Name': data.first },
      ...data.second && { 'Custom Second Prop Name': data.second },
      ...data.third  && { third: data.third },
      ...data.fourth && { fourth: data.fourth },
    });
    

提交回复
热议问题