分配对象属性时为DRY

ava*_*he1 0 javascript object

是否有一种优雅的方法可以消除所有parsedData.单词?在我看来,这不是很干。

function foo(parsedData) {
  const finalData = {
    KPP: parsedData.KPP,
    OGRN: parsedData.OGRN,
    principalShortName: parsedData.name.short,
    principalFullName: parsedData.name.full,
    principalLegalAddress: parsedData.address.legal,
    principalRealAddress: parsedData.address.real,
    OKATO: parsedData.OKATO,
    principalRegistrationDate: moment(parsedData.history.registration),
    principalTaxRegistrationDate: moment(parsedData.history.taxRegistration),
    OKOPF: parsedData.OKOPF,
    OKVED: parsedData.OKVED,
    headFullName: parsedData.head.fullName,
    headTitle: parsedData.head.fullName,
  });
}
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以尝试对象分解。参考:https//eslint.org/docs/rules/prefer-destructuring

function foo({KPP, OGRN, name, address, OKATO, history, OKOPF, OKVED, head}) {
  const finalData = {
    KPP: KPP,
    OGRN: OGRN,
    principalShortName: name.short,
    principalFullName: name.full,
    principalLegalAddress: address.legal,
    principalRealAddress: address.real,
    OKATO: OKATO,
    principalRegistrationDate: moment(history.registration),
    principalTaxRegistrationDate: moment(history.taxRegistration),
    OKOPF: OKOPF,
    OKVED: OKVED,
    headFullName: head.fullName,
    headTitle: head.fullName,
  });
}
Run Code Online (Sandbox Code Playgroud)

对于源名称和目标名称相同的属性,使用简写属性表示法可以进一步改善:

function foo({KPP, OGRN, name, address, OKATO, history, OKOPF, OKVED, head}) {
    const finalData = {
        KPP,
        OGRN,
        principalShortName: name.short,
        principalFullName: name.full,
        principalLegalAddress: address.legal,
        principalRealAddress: address.real,
        OKATO,
        principalRegistrationDate: moment(history.registration),
        principalTaxRegistrationDate: moment(history.taxRegistration),
        OKOPF,
        OKVED,
        headFullName: head.fullName,
        headTitle: head.fullName,
    });
}
Run Code Online (Sandbox Code Playgroud)