javascript - 分配对象属性时干燥
问题描述
有没有一种优雅的方法来摆脱所有的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,
});
}
解决方案
您可以尝试对象解构。参考: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,
});
}
推荐阅读
- python - 有没有一种有效的方法可以在大熊猫数据框中选择多行?
- c - 自定义 shell 无法识别传递给它的最后一个命令
- embedded-linux - Poky 提供的 BSP 与 Beaglebone black 的 meta-ti 之间的区别
- vb.net - 如何从字符串中解析 DateTime
- css - 如何根据根选择器有条件地设置 scss 变量值
- python - 值错误:具有多个元素的数组的真值不明确
- php - PHP 中音频和视频流 URL 的正确标头是什么?
- php - 如何使用 AJAX 向用户发送通知?
- python - 拖尾日志很慢
- ios - 如何按周获取与应用程序的用户连接数