JavaScript 有條件增加物件屬性的簡短寫法
從 The shortest way to conditional insert properties into an object literal 看到的。
例如,為了避免出現 undefined 的 property ,通常會這樣寫:
1const obj = {};
2if (input1) {
3 obj.prop1 = input1;
4}
5if (input2) {
6 obj.prop2 = input2;
7}
可以寫成:
1const obj = {
2 ...input1 && { prop1: input1 },
3 ...input2 && { prop2: input2 },
4};