我在下面的代码中没有得到预期的结果,只是想知道它是否是使用表达式在箭头函数语法中添加条件的正确方法。



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

最佳答案

据我了解,您希望过滤符合以下条件的对象


SettlementCode不应存在于drugPriceErrors数组中,或者
SettlementDesc应包含:


您可以按以下方式更正代码


首先,由于drugPriceErrors是数字数组,因此使用settlementCode+settlementCode转换为数字
如果条件评估为true,即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);

关于javascript - 如何在箭头函数表达式中编写if语句?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56330985/

10-09 22:54