Typescript/Javascript Conditionally Add members to object using spread op

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.


In that last line, you're setting the data property of the object to a new object, {datafield2: "hooahh"}.

That would be the equivalent of:

{
  data: { a: 1 }
  data: { b: 2 }
}

duplicate keys are overriden, so it becomes

{
  data: { b: 2 }
}

If you want to set data to a single object with conditional sub-keys of its own, you can do:

const test = {
    ...(someobj.field1 &&  {field1: someobj.field1}),
    ...(someobj.nofield && {nofield: "yowzee"}),
    ...(someobj.data && {data: {
        ...(someobj.data.datafield1 && {dataField1: "woohoo"}),
        ...(someobj.data.datafield2 && {dataField2: "hooahh"}),
    }}),
};