How to "migrate" one object to another object in JavaScript?



Given two object, named: ObjectA and ObjectB:

var ObjectA = {
    config1: "5",
    config2: "6",
    config3: "7"
var ObjectB = {
    config1: "1",
    config2: "2",
    config4: "3",
    config5: "4"

How can I copy from ObjectB to ObjectA so that ObjectA have the same properties of ObjectB while the values of properties in ObjectA is kept and values from ObjectB that doesn't exist in ObjectA is copied to ObjectA?

Expected result:

ObjectA = {
    config1: "5",
    config2: "6",
    config4: "3",
    config5: "4"
  • config3 is deleted since it doesn’t exist in ObjectB,
  • config4 with config5 are copied to ObjectA since those doesn’t exist in ObjectA,
  • and value in config1 with config2 are kept the same in ObjectA since those two exist in both of the object)


Use reduce:

ObjectA = Object.keys(ObjectB).reduce(
    (acc, key) => ({ ...acc, [key]: ObjectA[key] ?? ObjectB[key]}), {}

This will use the keys from ObjectB, take values from ObjectA, when they exist (with fallback to ObjectB), and populate an empty object with the results.

Answered By – fast-reflexes

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More