0

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"
    }
  }
]}
Lajtovo
  • 85
  • 1
  • 9

1 Answers1

1

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

Edit - I found this function which achieves what you need, not just overwrite the properties.

function realMerge(to, from) {

    for (let n in from) {

        if (typeof to[n] != 'object') {
            to[n] = from[n];
        } else if (typeof from[n] == 'object') {
            to[n] = realMerge(to[n], from[n]);
        }
    }
    return to;
};

I tested the output here and it produces:

[
  {
    key: 'A',
    content: {
      field1: 'updated sample text A',
      field2: 'another sample text A',
      field3: 'added text A'
    }
  },
  {
    key: 'B',
    content: { field1: 'sample text B', field2: 'another sample text B' }
  }
]
Craig
  • 64
  • 9
  • 1
    there is no field2 in object 'A' ("another sample text A") – Lajtovo Nov 20 '21 at 20:07
  • Good point. On reflection this is overwriting all the properties of the object in the array, and doesn't retain any unchanged properties. – Craig Nov 20 '21 at 23:39
  • I found this, which might help. https://stackoverflow.com/a/171455/16631804 – Craig Nov 20 '21 at 23:46