Add property to object when it's not null

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

    Non-inline solution

    If you don't need to add the value inline, it is pretty straightforward and clean to write your assignment like this.

    const val1 = 1
    const val2
    const data = {}
    
    val1 && (data.a = val1) // 1
    val2 && (data.b = val2) // Not added
    // data = { a : 1 }
    

    NOTE: This will not work if the value is falsey

提交回复
热议问题