如何在箭头函数表达式中编写if语句?

时间:2019-05-27 18:36:22

标签: javascript arrays ecmascript-6

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

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

1 个答案:

答案 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);