After creating a function that converts an object to an array where each element contains the ID of the object, I encountered a new requirement. The current function works great with the following code:
const objectToArray = <T>(object: { [id: string]: T }): (T & { id: string })[] => {
return Object.keys(object).map((key) => ({ id: key, ...object[key] }))
}
For example,
{ a: { value: 1 }, b: { value: 2 } }
would be converted into [{ id: 'a', value: 1 }, { id: 'b', value: 2 }]
.
The challenge now is to introduce a second parameter called idField
, which specifies the field name in the object to use as the ID field in the returned objects. For instance, setting idField
as userId
should yield
[{ userId: 'a', value: 1 }, { userId: 'b', value: 2 }]
.
I have managed to implement this logic within the function, but determining the appropriate return type has proven difficult:
export const objectToArray = <T>(object: { [id: string]: T }, idField: string): ???[] => {
return Object.keys(object).map((key) => ({ [idField]: key, ...object[key] }))
}
I initially tried setting the return type as
(T & { [idField]: string })[]
, only to receive the error A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.
.