我需要“瘦下来”并且将对象列表的属性减少很多,但仍然很多。我的代码如下:
function reduceSpeakersData(speakers: Speaker[]) {
return speakers.map(function(speaker: Speaker) {
//return speaker;
return ({
id: speaker.id,
firstName: speaker.firstName,
lastName: speaker.lastName,
imageUrl: speaker.imageUrl,
company: speaker.company
})
});
}
我知道我是否有
firstName: firstName
我可以做到
firstName
但不确定我能做什么
firstName: speaker.firstName
建议?
答案 0 :(得分:1)
可能会增加一些破坏性对象的概念
const reduceSpeakersData = (speakers: Speaker[]) => {
return speakers.map(({ id, firstName, lastName, imageUrl, company }: Speaker) => ({
id,
firstName,
lastName,
imageUrl,
company
}));
};
答案 1 :(得分:1)
如果您只想浅克隆,那么...
speakers.map(speaker => ({ ...speaker }))
如果您需要排除某些属性,则可以进行结构分解:
speakers.map(({ to, exclude, ...speaker }) => speaker)
但是,如果您需要排除必须包含的尽可能多的值,则没有捷径可走。您可以使用一个助手,例如:
const pick = (head, ....tail) => obj => !head ? {} : Object.assign(pick(...tail), { [head]: obj[head] });
speakers.map( pick("id", "firstName", /*...*/) )
答案 2 :(得分:0)
您可以在参数列表中使用解构和箭头功能:
function reduceSpeakersData(speakers: Speaker[]) {
return speakers.map(({id, firstName, lastName, imageUrl, company}: Speaker) =>
({id, firstName, lastName, imageUrl, company})
);
}