我在下面的代码中没有得到预期的结果,只是想知道它是否使用表达式在箭头函数语法中添加条件的正确方法。
const drugPriceErrors = [99, 85];
Case#1
const messages = [{
settlementCode: "99",
settlementDesc: "test:test"
}]
Case#2
const messages = [{
settlementCode: "77",
settlementDesc: "test"
}
];
Case#3
const messages = [{
settlementCode: "66",
settlementDesc: "test:test"
}]
function validateEntries(messages) {
if (!messages) {
return []
};
let filteredMsg = messages.filter((item) => {
if (!drugPriceErrors.includes(item.settlementCode)) {
item.settlementDesc.includes(":")
} else {
return;
}
});
return filteredMsg;
};
console.log(validateEntries(messages));
预期输出
Case#1 output should be
[{
settlementCode: "99",
settlementDesc: "test:test"
}]
Case#2 output should be
[]
Case#3 output
[{
settlementCode: "66",
settlementDesc: "test:test"
}]
答案 0 :(得分:2)
据我了解,您希望过滤符合以下条件的对象
SettlementCode
不应存在于drugPriceErrors
数组 OR SettlementDesc
应该包含:
您可以按照以下步骤更正代码
drugPriceErrors
是数字数组,因此请使用settlementCode
将+settlementCode
转换为数字settlementCode
中存在drugPriceErrors
,则返回true settlementDesc
是否包含:
const drugPriceErrors = [99,85];
const messages = [ {settlementCode:"99", settlementDesc: "test:test" }, {settlementCode:"66", settlementDesc: "test:test" },{settlementCode: "77",settlementDesc: "test"}];
function validateEntries(messages) {
if (!messages) {
return []
};
let filteredMsg = messages.filter((item) => {
if (drugPriceErrors.includes(+item.settlementCode)) return true;
else return item.settlementDesc.includes(":");
});
return filteredMsg;
};
console.log(validateEntries(messages));
此外,您还可以按照以下步骤简化代码
const drugPriceErrors = [99,85];
const messages = [ {settlementCode:"99", settlementDesc: "test:test" }, {settlementCode:"66", settlementDesc: "test:test" },{settlementCode: "77",settlementDesc: "test"}];
const result = messages.filter(v => drugPriceErrors.includes(+v.settlementCode) || v.settlementDesc.includes(":"));
console.log(result);