I am trying to conditionally add members to an object using the method prescribed here
Here is my code:
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);
This works great except that the last conditional overwrites data.datafield1. Its as if it re-creates the inner data objects. Any ideas how to resolve this?