Pacman
Pacman

Reputation: 2245

JS copy one object to another

I have the following object:

myModel = 
    {  
           Id: '',
           Category :'',
           Values: {
             userName: '',
             pasword: '',
             address: ''
           }
        }

newModel may look like this:

{
Version : "12.1",
Values : {
 "somenewProp" : "with a value"
}

I want myModel to look like this at the end of this merge:

myModel = 
        {  
               Id: '',
               Category :'',
               Version : "12.1",
               Values: {
                 userName: '',
                 pasword: '',
                 address: '',
                 "somenewProp" : "with a value"
               }
            }

I have the exact same object format with values that I want to merge, I am doing the following:

this.myModel = Object.assign(this.myModel, ...newModel);

MyModel doesnt change, I need to be able to merge new properties and assign properties from the newModel into myModel

Upvotes: 0

Views: 64

Answers (2)

Sajith Edirisinghe
Sajith Edirisinghe

Reputation: 1727

Assume;

myModel = {  
  Id: '',
  Category :'',
  Values: {
    userName: '',
    pasword: '',
    address: ''
  }
}

subModel =  {
  Version : "12.1",
  Values : {
    "somenewProp" : "with a value"
  }
}

Then newModel = {...myModel, Version: subModel.Version, Values: {...subModel.Values, ...myModel.Values}} will give you the result you want. Although, the readability of the code would be poor.

Upvotes: 0

Fathy
Fathy

Reputation: 5209

Object.assign is not recursive, nothing in the ECMAScript standard library offers recursive merging of two objects. You need to either :

  • Write your own recursive merge function
  • Use a third party library (eg. merge, lodash.merge, etc..)

Upvotes: 1

Related Questions