最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Extract this nested ternary operation into an independent statement - Stack Overflow

programmeradmin1浏览0评论

I am getting the above error with the example code below, I am quite new to nested ternary operations so your help would be appreciated. Example code below:

Car4 = {
  data: {
    CoverBasis: item.coverBasis() || "Client",
    IncludeInPackage: item.canBeIncludedInPackage() ?
      (item.includeInPackage() && totalPolicies > 1 ? "Yes" : "No") : "No"
  }
};

I am getting the above error with the example code below, I am quite new to nested ternary operations so your help would be appreciated. Example code below:

Car4 = {
  data: {
    CoverBasis: item.coverBasis() || "Client",
    IncludeInPackage: item.canBeIncludedInPackage() ?
      (item.includeInPackage() && totalPolicies > 1 ? "Yes" : "No") : "No"
  }
};

Share Improve this question edited Aug 13, 2021 at 9:36 pilchard 13k5 gold badges12 silver badges26 bronze badges asked Aug 13, 2021 at 9:35 aaishaaaisha 511 gold badge2 silver badges3 bronze badges 1
  • 4 You don't need this to be nested, it is 'yes' if all are true, or 'no' if any is false (in order) item.canBeIncludedInPackage() && item.includeInPackage() && totalPolicies > 1 ? "Yes" : "No"; – pilchard Commented Aug 13, 2021 at 10:03
Add a ment  | 

3 Answers 3

Reset to default 0

I think the error tells you to move the nester ternary operator totalPolicies > 1 ? "Yes" : "No" in the separated variable, like this:

const areTotalPoliciesBiggerOne = totalPolicies > 1 ? "Yes" : "No";
Car4 = {
  data: {
    CoverBasis: item.coverBasis() || "Client",
    IncludeInPackage: item.canBeIncludedInPackage() ?
      (item.includeInPackage() && areTotalPoliciesBiggerOne) : "No"
  }
};

I'm guessing it's sonarlint that throws warning/error. It's actually the dual nested ternary operator that increases the code plexity that's what sonarlint is suggesting IMO.

Doing it this way should solve the issue.

const itemIncludeInPackageAndTotalPolicies = (item.includeInPackage() && totalPolicies > 1 ? "Yes" : "No");

Car4 = {
  data: {
    CoverBasis: item.coverBasis() || "Client",
    IncludeInPackage: item.canBeIncludedInPackage() ?
      itemIncludeInPackageAndTotalPolicies : "No"
  }
};

You need to put yes or not in a <div></div>

 `totalPolicies > 1 ? <div>"Yes"</div>: 
<div>No</div>`
发布评论

评论列表(0)

  1. 暂无评论