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

I am getting the above error with the example code below, I am quite new to nested ternary operations s

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>`

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745182658a4615490.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信