Search code examples
javascriptjsonobject

How to merge two Object of Object in JavaScript (NodeJS)


I have multiple objects:

const obj1 = {
  db: {
    url: "mongodb://localhost:27017",
  },
};

const obj2 = {
  db: {
    user: "admin",
  },
};

const obj3 = {
  token: {
    auth: {
      secret: "*****",
    },
  },
};

How can merge into a single object like this:

{
    db: {
        url: "mongodb://localhost:27017",
        user: "admin"
    },
    token: {
        auth: {
            secret: "*****"
        }
    }
}

I just tried something like this: Object.assign(obj1, obj2) but is not what I want.


Solution

  • I suggest correcting the objects that aren't valid, as pointed out in the comments. Other than this, the following function works for as many objects as you want.

    const obj1 = {
      db: {
        url: "mongodb://localhost:27017",
      },
    };
    
    const obj2 = {
      db: {
        user: "admin",
      },
    };
    
    const obj3 = {
      token: {
        auth: {
          secret: "*****",
        },
      },
    };
    
    function merge() {
      const result = {};
    
      for (let i = 0; i < arguments.length; i++) {
        const obj = arguments[i];
    
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (typeof obj[key] === "object") {
              result[key] = merge(result[key], obj[key]);
            } else {
              result[key] = obj[key];
            }
          }
        }
      }
    
      return result;
    }
    
    const merged = merge(obj1, obj2, obj3);
    console.log(merged);