Home > OS >  Is there a shorthand for mapping object parameters to another object in TypeScript?
Is there a shorthand for mapping object parameters to another object in TypeScript?

Time:04-06

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.

CodePudding user response:

If you are 100% sure that the properties always match, you can try this:

response.rooms.push({...doc})

CodePudding user response:

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 functio, 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:

type Primitive = string | number | boolean; 
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));
  • Related