我想使用filter而不是lodash _forEach重构代码,下面的filter代码未返回预期的响应。知道这里的错误实现是什么吗?
main.js
const response = [];
const data = [{
"isBrand": true,
"drugName": "Lipitor",
"specialtyPrice": {}
},
{
"isBrand": false,
"drugName": "Atorvastatin Calcium",
"drugStrength": "80mg",
"drugForm": "Tablet",
"mailPrice": {
"totalQuantity": 90,
"rejectMessage": [{
"settlementCode": "99",
"settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
}]
},
"retailPrice": {
"totalQuantity": 30,
"rejectMessage": [{
"settlementCode": "99",
"settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
}]
},
"specialtyPrice": {}
}
];
_.forEach(data, function(drug) {
if (drug.retailPrice !== undefined || drug.mailPrice !== undefined) {
response.push(drug);
}
});
const filterItems = data.filter(item => item.retailPrice && item.mailPrice)
console.log(filterItems);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
预期结果
[{
"isBrand": false,
"drugName": "Atorvastatin Calcium",
"drugStrength": "80mg",
"drugForm": "Tablet",
"mailPrice": {
"totalQuantity": 90,
"rejectMessage": [{
"settlementCode": "99",
"settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
}]
},
"retailPrice": {
"totalQuantity": 30,
"rejectMessage": [{
"settlementCode": "99",
"settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
}]
},
"specialtyPrice": {}
}
];
答案 0 :(得分:0)
这应该有效。
var objNotEmpty = function(obj){
return Object.keys(obj).length > 0;
},
objHasPrice = function(obj){
return obj.hasOwnProperty("mailPrice") && obj.hasOwnProperty("retailPrice");
};
const filterItems = data.filter( item => return objHasPrice(item) && objNotEmpty(item.mailPrice) && objNotEmpty(item.retailPrice);
答案 1 :(得分:0)
您可以像这样简单地进行Array.forEach:
data.forEach(d => (d.retailPrice || d.mailPrice) ? response.push(d) : null)
所以它看起来像这样:
const response = [];
const data = [{
"isBrand": true,
"drugName": "Lipitor",
"specialtyPrice": {}
},
{
"isBrand": false,
"drugName": "Atorvastatin Calcium",
"drugStrength": "80mg",
"drugForm": "Tablet",
"mailPrice": {
"totalQuantity": 90,
"rejectMessage": [{
"settlementCode": "99",
"settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
}]
},
"retailPrice": {
"totalQuantity": 30,
"rejectMessage": [{
"settlementCode": "99",
"settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
}]
},
"specialtyPrice": {}
}
];
data.forEach(d => (d.retailPrice || d.mailPrice) ? response.push(d) : null)
const filterItems = data.filter(item => item.retailPrice && item.mailPrice)
console.log(filterItems);