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 --
  • 54,565
  • 8
  • 62
  • 98
neowenshun
  • 760
  • 1
  • 5
  • 12

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
  • 9,107
  • 3
  • 12
  • 28
Sushanth --
  • 54,565
  • 8
  • 62
  • 98