如何将一个对象的属性映射到另一个对象?

时间:2018-11-25 08:16:33

标签: javascript schema lodash normalizr

我知道在这个问题上有很多问题,但是我不知道如何在我的情况下适用。

代码如下:

const mailDocumentSchema = new schema.Entity('mailDocuments', {}, { idAttribute: 'identifier' });
const mailSchema = new schema.Entity('mails', { emailDocument: [mailDocumentSchema] }, { idAttribute: 'identifier' });
const mailAccountSchema = new schema.Entity('mailAccounts', { mails: [mailSchema] }, { idAttribute: 'address' });

const mailMapper = (item: any): Mail => ({
  id: item.identifier,
  title: item.subject,
  documents: item.emailDocument,
  subject: item.realSubject,
  receiver: item.receiver,
  createdDate: item.createdDate,
  sendDate: item.sendDate,
  body: item.body
});

const mailDocumentMapper = (item: any): MailDocument => ({
  id: item.identifier,
  docId: item.oldDocId,
  name: item.name,
  createdDate: item.createdDate,
  bodyStatus: item.bodyStatus
});

export const undefinedDocumentsMapper = (response: any[]): NormalizedMailbox => {
  const undefinedDocuments = map(groupBy(response, item => item.receiver), (item, key) => ({ name: null, address: key, mails: item }));
  const normalizedResponse = normalize(undefinedDocuments, [mailAccountSchema]);
  return {
    mailAccounts: Object.values<MailAccount>(normalizedResponse.entities.mailAccounts),
    mails: Object.values<any>(normalizedResponse.entities.mails).map(mailMapper),
    mailDocuments: Object.values<any>(normalizedResponse.entities.mailDocuments).map(mailDocumentMapper) 
  };
};

API响应为:

[
   { identifier: "...", title: "...", receiver: "...", emailDocuments: [{...}] },
   ...
]

我想要的是将receiver实体对象的titlemails属性映射到mailDocuments实体对象。

结果是像这样获得mailDocuments个实体对象:

{
  id: "...",
  docId: "...",
  name: "...",
  createdDate: "...",
  bodyStatus: ...,
  title: "...",
  receiver: "..."
}

如何做到这一点?

1 个答案:

答案 0 :(得分:0)

如果我理解正确,则可以执行以下操作:

mails.forEach(mail => {
  mail.documents.forEach(document => {
    document.receiver = email.receiver
    document.title = email.title
  })
})