试图从数组对象中删除相似属性,但是无法重新声明抛出错误的作用域变量,如何在不更改原始数组的情况下使用任何更好的方法从对象中删除相似属性?
main.js
const loggerResponse = transformedResponse.map(({ drugName, mailPrice,retailPrice, ...rest }) => {
const { copayEmployer, ...mailPriceRest } = mailPrice;
const { copayEmployer, ...retailPriceRest } = retailPrice;
return { ...rest, mailPrice: mailPriceRest , retailPrice: retailPriceRest};
})
transformedResponse
[
{
"isBrand": true,
"drugName": "Lipitor",
"drugStrength": "80 mg",
"drugForm": "Tablet",
"mailPrice": {
"copayEmployer": 0,
"prop2": "test"
},
"retialPrice": {
"copayEmployer": 0,
"prop2": "test"
}
}, {
"isBrand": true,
"drugName": "Metformin",
"drugStrength": "500 mg",
"drugForm": "Tablet",
"mailPrice": {
"copayEmployer": 50,
"prop2": "test"
},
"retailPrice": {
"copayEmployer": 0,
"prop2": "test"
}
}
]
预期输出
[
{
"isBrand": true,
"drugStrength": "80 mg",
"drugForm": "Tablet",
"mailPrice": {
"prop2": "test"
},
"retialPrice": {
"prop2": "test"
}
}, {
"isBrand": true,
"drugStrength": "500 mg",
"drugForm": "Tablet",
"mailPrice": {
"prop2": "test"
},
"retailPrice": {
"prop2": "test"
}
}
]
答案 0 :(得分:0)
实际上,您的方法很棒,但是您需要进行一些更改,请尝试克隆对象而不是直接使用它,就像:
const loggerResponse = transformedResponse.map(({ drugName, mailPrice, retailPrice, ...rest }) => {
const { copayEmployer, ...mailPriceRest } = mailPrice || {};
const { copayEmployer: copayEmployerRetail, ...retailPriceRest } = retailPrice || {};
return { ...rest, mailPrice: { ...mailPriceRest, copayEmployer } , retailPrice: { ...retailPriceRest, copayEmployer: copayEmployerRetail }};
})
应该可以解决问题。
答案 1 :(得分:0)
该解决方案如何?
const loggerResponse = function transform (originalArray) {
originalArray.map( element => {
delete element.drugName;
delete element.mailPrice.copayEmployer;
delete element.retialPrice.copayEmployer;
});
return originalArray;
}
const expectedArray = loggerResponse(transformedResponse);
console.log(expectedArray);
当然,如果需要,您可以克隆原始数组。并且请注意,仅使用slice()
,spread运算符等方法进行克隆将不会对其进行深层克隆,但是您可以使用以下代码来实现:
const deepClone = JSON.parse(JSON.stringify(transformedResponse));
然后,您可以在克隆的Array上执行所有操作,而无需触摸原始阵列。