TypeScript Object | How to Merge Objects in TypeScript

In this article, we will learn How to Merge Objects in TypeScript. To merge objects, you can use the following.

Merge Objects in TypeScript
  • spread operator
  • Object.Assign
  • Lodash merge function        

Using spread operator

In TypeScript, the Easiest way to merge objects using the spread operator. The spread operator is a feature of ES6, you will need to target ES6 or later when you compile.

Here is an Example:

const empNameObject = {
  name : 'John',
  lastname: 'pointing'
};

const empAddressObject={
  street :'Main 10th Road',
  city : 'NY'
};

const mergeObject = {
  ...empNameObject,...empAddressObject
};

console.log(mergeObject);

In the above example, the mergeObject is a new object that contains all the properties from empNameObject and em AddressObject.

Output:

{
name: ‘John’,
lastname: ‘pointing’,
street: ‘Main 10th Road’,
city: ‘NY’
}

Using Object.assign

The “Object.assign” method copies all the enumerable & own properties from one or many source objects to a target object and it is a built-in function.

This function can work similarly to a spread operator.

const empNameObject = {
  name : 'John',
  lastname: 'pointing'
};

const empAddressObject={
  street :'Main 10th Road',
  city : 'NY'
};

const empSalaryObject={
  salary : 50000,
  increment : 10
};


const mergeObjectAssign = Object.assign({}, empNameObject,empAddressObject,empSalaryObject);
 
console.log(mergeObjectAssign);

Output:

{
  name: 'John',
  lastname: 'pointing',
  street: 'Main 10th Road',
  city: 'NY',
  salary: 50000,
  increment: 10
}

Using Lodash Merge Function

The “Lodash” merge function is used to merge two or more objects together, creating a new object that contains the properties and values from the source objects It merges complex values.

import * as lodashMerge from 'lodash';
const lodashObject ={
  Email : "Fleming@test.com",  
  DisplayName: "Flemin",
  Address : {
          firstName : "Flemin@test.com",
          lastName: "Fleming",
          street:"Abc",
          city:"New york",
          state :"NY",
          zipCode: "2341"
}
};

const lodashObjectsalary ={
  salary : 45000,
  increment:{
    firstQ : 10,
    secondQ : 15
  }
};
const MergeLodashObject =  lodashMerge.merge(lodashObject,lodashObjectsalary); 

console.log(MergeLodashObject);

Output:

{
  Email: 'Fleming@test.com',
  DisplayName: 'Flemin',
  Address: {
    firstName: 'Flemin@test.com',
    lastName: 'Fleming',
    street: 'Abc',
    city: 'New york',
    state: 'NY',
    zipCode: '2341'
  },
  salary: 45000,
  increment: { firstQ: 10, secondQ: 15 }
}

More Article – remove duplicates from an Array in TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *