【问题标题】:Can I chain these 2 ".last" lodash calls?我可以链接这 2 个“.last”lodash 调用吗?
【发布时间】:2019-08-31 09:28:57
【问题描述】:

我有一个带有一系列信用报告历史记录的贷款对象,每个信用报告都有一系列信用评分。我想获取上次信用报告的最后信用评分

let creditReportHistory = loanInfo.creditReportHistory;
let lastReport = creditReportHistory ? _.last(creditReportHistory) : null;
let lastScore = lastReport ? _.last(lastReport.creditScores) : null;
return (
  loanInfo.fico !== null &&          // has a score
  _.isArray(creditReportHistory) &&  // history is an array
  creditReportHistory.length > 0 &&  // at least one credit report
  lastScore === null                 // last report has a last score that is null
);

上面的代码基本上需要知道最后一个report的最后一个score是否为null。其他条件不依赖于 lodash "last()" 调用。

【问题讨论】:

    标签: angular lodash


    【解决方案1】:

    我认为这应该是你的解决方案,但我没有数据集来测试它,所以我只是想复制你的逻辑。

    // Your current code:
    let creditReportHistory = loanInfo.creditReportHistory;
    let lastReport = creditReportHistory ? _.last(creditReportHistory) : null;
    let lastScore = lastReport ? _.last(lastReport.creditScores) : null;
    return (
      loanInfo.fico !== null &&          // has a score
      _.isArray(creditReportHistory) &&  // history is an array
      creditReportHistory.length > 0 &&  // at least one credit report
      lastScore === null                 // last report has a last score that is null
    );
    
    // Updated:
    const lastScore = _.chain(loanInfo.creditReportHistory)
      .last()
      .flatMap((lastReport) => lastReport.creditScores)
      .last()
      .value();
    
    return (
      loanInfo.fico !== null
      && lastScore 
    );

    【讨论】:

    • 好的,我把那个代码块带进去了,在编译时遇到一个错误,即“{}”类型上不存在属性“flatMap”。我的数据结构(简化)是这样的:loanInfo 具有 creditReportHistory 属性,它是 CreditReportItems 的数组。 CreditReportItem 有一个字符串类型的 ID 和一个数字数组的 creditScores 属性。所以最后一个 creditReportHIstory 项目有一个数组分数作为数字。还没有弄清楚为什么编译器不喜欢将 .flatMap() 应用于最后一个 creditReportHistory。
    • 如果您在编译时收到该消息,那么这就是 TypeScript 抱怨它无法推断类型,因此您将不得不进行一些显式类型转换。另一种选择是将 Lodash 类型作为应用程序的 package.json 文件中的 devDependencies 导入项目。这可能有助于 TypeScript 进行类型推断。包应该是@types/lodash
    猜你喜欢
    • 2014-03-02
    • 2020-06-04
    • 2021-10-25
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    相关资源
    最近更新 更多