How to Convert an Array of Objects into Object in TypeScript ?
Last Updated :
12 Feb, 2024
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"
}
Share your thoughts in the comments
Please Login to comment...