-1

I have an obejct:

obj1 = {
id: 123,
name: "ABC test",
desc: "SPme test sdesctiption",
data: [{name:"data1"}],
createdBy: "Some person",
updatedBy: "Some persone22"
}

Now when we edit the details of this data from client side, we need to update only those fields from the object that has been changed. ex:

updatedObj = {
    id: 123,
    name: "ABC12222222 test", // changed
    desc: "SPme test sdesctiption",
    data: [{name:"data1"}],
    createdBy: "Some person",
    updatedBy: "Some persone22"
    }

In above case I only want to change the name, but this data can be dynamic and based on what user changes, we need to update only thoe fields in the obj1

I tried :

newObj = Object.assign(obj1, {updatedObj})

but this inserts all new object inside obj1. I tried using Shallow copy of objects but that did not quite work.

any ideas how this can be achieved?

user1234
  • 3,000
  • 4
  • 50
  • 102
  • 1
    Example of coding [difference between 2 objects](https://gomakethings.com/getting-the-differences-between-two-objects-with-vanilla-js/). – jarmod Aug 29 '22 at 17:07
  • Don't put `{}` around `updatedObj`. It's already an object, you don't have to wrap it again. – Barmar Aug 29 '22 at 17:07
  • Why does `updatedObj` have all the fields instead of just the changed fields? – Barmar Aug 29 '22 at 17:08
  • 1
    You'll need to create a [deep copy](https://developer.mozilla.org/en-US/docs/Glossary/Deep_copy). There are various ways to do this. The most common way is outlined in the previous link. [Here](https://stackoverflow.com/a/122704/10601203) is a StackOverflow answer that goes a bit more in-depth on the subject. – Jesse Aug 29 '22 at 17:09

1 Answers1

0

Since updatedObj have all the fields instead of just the changed fields

newObj = updatedObj
ManuelMB
  • 1,254
  • 2
  • 8
  • 16