I was exploring a method for conditionally adding members to an object, which I found here
Below is the code I came up with:
const theobj = {
field1: "hello",
field2: 1,
data: {
datafield1: "world",
datafield2: 2
},
field3: "yowzee"
};
let someobj: any;
someobj = theobj;
const test = {
...(someobj.field1 && {field1: someobj.field1}),
...(someobj.nofield && {nofield: "yowzee"}),
...(someobj.data?.datafield1 && {data: {dataField1: "woohoo"}}),
...(someobj.data?.datafield2 && {data: {datafield2: "hooahh"}}), // overwrites the above
};
console.log(test);
The only issue I encountered is that the last conditional statement overwrites data.datafield1. It seems to recreate the inner data objects. Any suggestions on how to fix this?