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?
>Solution :
Yes, it’s happening exactly what you’re thinking, this is why you need a reference from a previous value of the data object.
const test = {
...(someobj.field1 && { field1: someobj.field1 }),
...(someobj.nofield && { nofield: "yowzee" }),
...(someobj.data.datafield1 && { data: { dataField1: "woohoo" }}),
...(someobj.data.datafield2 && { data: { ...someobj.data, datafield2: "hooahh" }}), // doesn't overwrites the above.
};
By spreading someobj.data inside of itself, you are ensuring that it has his previous value.