You have the option to employ Object.fromEntries
.
type TypeX = {
x: number;
y: number;
z: number;
};
type TypeY = {
p: number;
q: number;
r: number;
};
declare const oldData: { [key: string]: TypeX };
const newData: { [key: string]: TypeY } = Object.fromEntries(
Object.entries(oldData).map(([key, value]) => [
key,
{
p: value.x,
q: value.y,
r: value.z
}
])
);
Playground Link
To provide further detail, Object.fromEntries
functions as a reverse operation of Object.entries
, transforming an array comprising [key, value]
pairs into an object matching keys with their corresponding values.
In this context, we initially use Object.entries
and then utilize a map
function to convert each item from [key, value]
to [key, newValue]
, which is subsequently fed into Object.fromEntries
.
Please bear in mind that Object.fromEntries
was included in ES2019. In cases where your runtime environment lacks ES2019 support, integrating a polyfill like npm:object.fromentries becomes necessary, along with specifying
"lib": ["ES2019"]
or later within your
tsconfig.json
The unnecessary type assertion as TypeY
has been removed to avoid suppressing errors such as overlooking or misspelling properties defined by TypeY
. TypeScript's ability for type inference stands out as one of its key features.
Your inclination towards utilizing map
and reduce
aligns well with best practices. While map
is employed here, reduce
was commonly used before the introduction of Object.fromEntries
to achieve similar outcomes.