gpt4 book ai didi

javascript - 如何使用es6的filter或reduce来破坏对象属性?

转载 作者:行者123 更新时间:2023-12-02 23:38:50 27 4
gpt4 key购买 nike

尝试使用reduce方法删除对象属性,但它没有返回预期的响应,在下面的用例中使用什么是正确的方法?过滤或减少?

main.js

const filtered = Object.keys(transformedResponse).reduce((res, key) => {

delete res.drugName;
delete res.mailPrice. copayEmployer
delete res.retailPrice. copayEmployer
return res;
}, {});

转换后的响应

const 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"
}
}

]

最佳答案

您可以使用map过滤结果

var x = transformedResponse.map((obj) => {
return {
"isBrand": obj.isBrand,
"drugStrength": obj.drugStrength,
"drugForm": obj.drugForm,
"mailPrice": {
"prop2": obj.mailPrice.prop2
},
"retailPrice": {
"prop2": obj.retailPrice.prop2
}
}
});

console.log(x);

Map 迭代给定数组中的每个项目并返回一个新数组。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

关于javascript - 如何使用es6的filter或reduce来破坏对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56173304/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com