首页 > 解决方案 > 分配对象属性时干燥

问题描述

有没有一种优雅的方法来摆脱所有的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,
  });
}

标签: javascriptobject

解决方案


您可以尝试对象解构。参考: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,
  });
}

对于源名称和目标名称相同的属性,它通过简写属性表示法进一步改进:

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,
    });
}

推荐阅读