Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript/Javascript Conditionally Add members to object using spread op

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading