1

I have 2 objects .

userprofile = {
  id: 1,
  email: hello @gmail.com,
  user: {
    id: 1,
    username: test,
  }

}

userprofile2 = {
  email: bye @gmail.com,
  user: {
    username: testtest,
  }
}

What i wish to do is to merge userprofile and userprofile2 , or in a sense using userprofile2 to override userprofile.

Here is what i wish to obtain:

updatedprofile = {
  id: 1,
  email: bye @gmail.com,
  user: {
    id: 1,
    username: testtest,
  }
}

The application for this problem is because i have an update form which uses redux saga . The change in data is userprofile2 while the previous data is userprofile.

Is there a simple efficient way to do this?

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
neowenshun
  • 860
  • 1
  • 7
  • 21

1 Answers1

0

You could use the spread operator. As the ... operator only performs a shallow merge, you will have to spread the nested user property as well.

const userprofile = {
  id: 1,
  email: "hello @gmail.com",
  user: {
    id: 1,
    username: "test",
  }

}

const userprofile2 = {
  email: "bye @gmail.com",
  user: {
    username: "testtest",
  }
}

const updatedProfile = {
   ...userprofile,
   ...userprofile2,

   user: {
     ...userprofile.user,
     ...userprofile2.user,
   }
};

console.log(updatedProfile)
Ramesh Reddy
  • 10,159
  • 3
  • 17
  • 32
Sushanth --
  • 55,259
  • 9
  • 66
  • 105