Open In App

How to Convert an Array of Objects into Object in TypeScript ?

Last Updated : 13 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are given an array of objects and we have to convert this array into a single object that contains all the properties of each object at a single level.

Example:

Input: arr[] = 
[
{key1: val1},
{key2: val2}
]
Output:
{
key1: val1,
key2: val2
}

Using Object.assign() with rest parameter

The Object.assign() method can be used to convert an array of objects into a single object by passing an empty object and using the rest parameter with the array to store its items into the empty object.

Syntax:

Object.assign(target, ...sources);

Example: The below code uses object.assign() method with rest parameter to convert an array of objects into a single object.

Javascript
interface obj {
  key1: string,
  key2: string,
  key3: string,
}

const arr: any[] =
  [
      { key1: 'value1' },
      { key2: 'value2' },
      { key3: 'value3' }
  ];

const res: obj =
  Object.assign({}, ...arr);
console.log(res);

Output:

{  
"key1": "value1",
"key2": "value2",
"key3": "value3"
}

Using Reduce() Method

The reduce() method can also be used to convert an array of object into a single object by passing a callback function with the logic used in the below example.

Syntax:

array.reduce(callback[, initialValue])

Example: The below code implements the reduce() method to convert an array of objects into a single object.

Javascript
interface obj {
  [key: string]: string;
}

const arr: obj[] =
  [
      { key1: 'value1' },
      { key2: 'value2' },
      { key3: 'value3' }
  ];

const res = (arr: obj[]) => {
  return arr.reduce((accum, curr) => {
      return { ...accum, ...curr };
  }, {});
};

console.log(res(arr));

Output:

{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}

Using a for…of loop

In this approach, we iterate over the array of objects using a for…of loop and merge each object’s properties into a single object.

Example:

JavaScript
interface MyObject {
    [key: string]: string;
}

const arr: MyObject[] = [
    { key1: 'value1' },
    { key2: 'value2' },
    { key3: 'value3' }
];

function convertArrayToObject(arr: MyObject[]): MyObject {
    const result: MyObject = {};
    for (const obj of arr) {
        for (const key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
                result[key] = obj[key];
            }
        }
    }
    return result;
}

console.log(convertArrayToObject(arr));

Output:

{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads