javascriptvue.jsspread-syntax

Javascript object spread with an object that may have undefined objects as data in its properties


Hey I'm trying to fill out an empty placeholder object (which in this case serves as a v-model for vue, but not important exactly to the case). The object that I'm expanding the original with may or may not have some objects inside it undefined, but i need to keep the structure of the first object no matter the structure of incoming one. For example Object 1

let object1 = { a : '', b : '', c : {name : 'Mark', title: 'Mr'}}

and Object 2 which will sometimes come like this

let object2 = { a : 'AAA', b : 'BBB', c : undefined}

I need to keep the structure of object 1 even if the other object has the property c undefined. In this case

let object1 = { a : 'AAA', b : 'BBB', c : {name : 'Mark', title: 'Mr'}}

Thanks


Solution

  • Try to spread the object2 as first item, then add property c as second :

      object1={...object2,c:object1.c}
    

    or

       object1={...object2,  c : object2.c ? object2.c : object1.c}