'Is there a shorthand for mapping object parameters to another object in TypeScript?
Example:
response.rooms.push({
maxPlayers: doc.maxPlayers,
ownderId: doc.ownderId,
roomId: doc.ownderId,
state: doc.state,
type: doc.type,
});
The parameters all have same name. The doc object also contains parameters that I don't want to map to rooms. Any ideas? Because this is a short one and it gets really annoying with larger objects.
Solution 1:[1]
The doc object also contains parameters that I don't want to map to rooms.
You'll have to explicitly declare what you want from doc at some point. For large objects adding a function, buildRoom, makes the desired shape still using dot access or destructuring in its implementation and may reduce tedium.
function buildRoom1(obj: typeof doc) {
const {
maxPlayers,
ownerId,
state,
type,
...
} = doc;
return {
maxPlayers,
ownerId,
roomId: doc.ownerId,
state,
type
};
}
response.rooms.push(buildRoom(doc));
Flamboyantly:
function pluck<T extends Record<PropertyKey, any>, K extends keyof T>(obj: T, ...fields: K[]) {
return fields.reduce((acc, field) => ({ ...acc, [field]: obj[field] }), {} as Pick<T, K>);
}
const room = pluck(doc, "ownderId", "state", "type", "maxPlayers");
response.rooms.push({ ...doc, roomId: room.ownderId });
then with more indirection:
function buildRoom2(obj: typeof doc) {
const props = pluck(obj, "ownderId", "state", "type", "maxPlayers");
return { ...props, roomId: props.ownderId };
}
response.rooms.push(buildRoom2(doc));
Solution 2:[2]
If you are 100% sure that the properties always match, you can try this:
response.rooms.push({...doc})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | sandrooco |
