简体   繁体   中英

How can I shorten this ternary operator?

I have code that stores information retrieved from a database.

Because my JavaScript code is Asynchronous and takes time to retrieve data, I am think it will store errors instead of data.

There is an existing helper function that checks for nested objects up to a high level. I want to make this function shorter and stop the ternary operator from ever returning '' .

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 : '';

If IsNestedObjectKeyPresent helper is mostly used for this purpose, a helper that returns empty string could be used instead:

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

This is what default value argument in safe navigation functions like Lodash get is for.

There's no need to use a ternary for same value as used in condition, it could be short-circuited:

const ratingWiseCounts = currentProjectDetails.ratingWiseCounts || '';

In case it's known that the only possibility for a value to be falsy is to be undefined , destructuring default value can be used:

const { ratingWiseCounts = '' } = currentProjectDetails;

you can use Short-circuit operators &&

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;

example

 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}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM