[英]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
. doc
object 还包含我不想 map 到rooms
的参数。 Any ideas?有任何想法吗? Because this is a short one and it gets really annoying with larger objects.
因为这是一个很短的对象,而且对于较大的对象来说真的很烦人。
If you are 100% sure that the properties always match, you can try this:如果您 100% 确定属性始终匹配,您可以试试这个:
response.rooms.push({...doc})
The doc object also contains parameters that I don't want to map to rooms.
文档 object 还包含我不想 map 到房间的参数。
You'll have to explicitly declare what you want from doc
at some point.您必须在某些时候明确声明您想要从
doc
获得什么。 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,
buildRoom
,使所需的形状在其实现中仍然使用点访问或解构,并可能减少单调乏味。
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.