如何缩短该三元运算符?

时间:2019-01-08 09:30:23

标签: javascript reactjs ternary-operator

我有用于存储从数据库检索到的信息的代码。

因为我的JavaScript代码是异步代码,并且需要花费一些时间来检索数据,所以我认为它将存储错误而不是数据。

有一个现有的帮助程序功能,可以检查嵌套对象的高级信息。我想使此函数更短,并阻止三元运算符返回''

const ratingAggregateCount = IsNestedObjectKeyPresent(currentProjectDetails, "ratingAggregate", "count") ? currentProjectDetails.ratingAggregate.count : '';

const ratingAggregateAverage = sNestedObjectKeyPresent(currentProjectDetails, "ratingAggregate", "average") ? currentProjectDetails.ratingAggregate.average.toFixed(1) : '';

const ratingWiseCounts = (!!currentProjectDetails.ratingWiseCounts ) ? currentProjectDetails.ratingWiseCounts : '';

2 个答案:

答案 0 :(得分:1)

如果IsNestedObjectKeyPresent辅助程序主要用于此目的,则可以使用返回空字符串的辅助程序:

const ratingAggregateCount = nestedObjectKeyOrEmptyString(currentProjectDetails, "ratingAggregate", "count");

这是安全导航功能(如Lodash get)中默认值参数的作用。

没有必要使用三进制值作为条件中使用的相同值,它可能会短路:

const ratingWiseCounts = currentProjectDetails.ratingWiseCounts || '';

如果已知值伪造的唯一可能性是undefined,则可以使用破坏性默认值:

const { ratingWiseCounts = '' } = currentProjectDetails;

答案 1 :(得分:0)

您可以使用短路操作符 &&

const ratingAggregateCount = IsNestedObjectKeyPresent(currentProjectDetails, "ratingAggregate", "count") && currentProjectDetails.ratingAggregate.count;

const ratingAggregateAverage = sNestedObjectKeyPresent(currentProjectDetails, "ratingAggregate", "average") && currentProjectDetails.ratingAggregate.average.toFixed(1);

const ratingWiseCounts = (!!currentProjectDetails.ratingWiseCounts ) && currentProjectDetails.ratingWiseCounts;

示例

const a = true && "assign";
const b = "something" && "assign";
const c = false && "not assign";
const d = undefined && "not assign";
const e = null && "not assign";
const f = "" && "not assign";

console.log({a,b,c,d,e,f});