Home > Software design >  Easiest way to update one object with another (sth a.k.a PATCH)
Easiest way to update one object with another (sth a.k.a PATCH)

Time:11-20

I have object A. I want to update this object with changes from object B.

  • If the field is not present in object B, it should be left unchanged
  • If there is a field in object B that is not present in object A, it preferably should not be added, but could be if this will simplify solution.

for example

o1 = {[
  { 
    key: "A", 
    content: {
      field1: "sample text A",
      field2: "another sample text A"
    }
  }, 
  { 
    key: "B", 
    content: {
      field1: "sample text B",
      field2: "another sample text B"
    }
  }
]}
o2 = [{ 
  key: "A", 
  content: {
    field1: "updated sample text A",
    field3: "added text A"
  }
}]

output:

o3 = {[
  { 
    key: "A", 
    content: {
      field1: "updated sample text A",
      field2: "another sample text A"
    }
  }, 
  { 
    key: "B", 
    content: {
      field1: "sample text B"
      field2: "another sample text B"
    }
  }
]}

CodePudding user response:

Use Object.assign()

I've just tested:

let o1 = [
    {
        key: "A",
        content: {
            field1: "sample text A",
            field2: "another sample text A"
        }
    },
    {
        key: "B",
        content: {
            field1: "sample text B",
            field2: "another sample text B"
        }
    }
    ]

let o2 = [{
    key: "A",
    content: {
        field1: "updated sample text A",
        field3: "added text A"
    }
}]

Object.assign(o1, o2);
console.log(o1);

getting an output:

[
  {
    key: 'A',
    content: { field1: 'updated sample text A', field3: 'added text A' }
  },
  {
    key: 'B',
    content: { field1: 'sample text B', field2: 'another sample text B' }
  }
]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

  • Related