Photo by Fili Santillán on Unsplash
Flattening Nested Objects in TypeScript: Combining Multiple 'Entries' Properties into a Single Object
Flattening an array is one of useful transformation on the data, mainly for the data obtained through pagination api responses.
Say we have a data of this format and we want to flatten it.
[
{
entries: {
'1': Object,
'2': Object
}
},
{
entries: {
'3': Object,
'4': Object,
}
},
{
entries: {
'5': Object,
'6': Object,
}
}
]
I am using TypeScript to do this. You can code it in the language of your choice.
To flatten this array of objects into a single object with all the entries
combined, you can use the reduce()
method.
interface Entry {
[key: string]: any; // replace `any` with the actual type of your objects
}
interface EntryWithEntries {
entries: {
[key: string]: Entry;
};
}
const arrayOfObjects: EntryWithEntries[] = [
{
entries: {
'1': { /* ... */ },
'2': { /* ... */ }
}
},
{
entries: {
'3': { /* ... */ },
'4': { /* ... */ },
}
},
{
entries: {
'5': { /* ... */ },
'6': { /* ... */ },
}
}
];
const flattenedEntries: { [key: string]: Entry } = arrayOfObjects.reduce((accumulator, current) => {
return { ...accumulator, ...current.entries };
}, {});
console.log(flattenedEntries);
In this example, we define two interfaces: Entry
, which represents the type of the objects in the entries
property, and EntryWithEntries
, which represents the type of the objects in the arrayOfObjects
array.
We then define a flattenedEntries
variable and use the reduce()
method to combine all the entries
properties into a single object. The reduce()
method takes a callback function that receives two parameters: accumulator
, which is the accumulated result of the previous iterations, and current
, which is the current element being processed.
Inside the callback function, we use the spread operator to merge the accumulator
and current.entries
objects into a new object, which is returned as the new accumulator
. At the end of the reduce()
method, we get an object that contains all the entries
properties combined, with the keys being the string keys of the original entries
properties.
I hope that helps!.... Will be back with another quick post.