I have this structure
const name = user.name;
const email = user.email;
const doc = user.doc;
const paramsSearch = req?.params?.search;
const search = …;
I want to transform search in a ternary like:
const search = paramsSearch === user.name ? …
if its equal to name or email or doc then search will be one of them, else return an empty string
I have tried the if else condition but i need it in ternary
You could try something like this.
const search =
paramsSearch === name
? name
: paramsSearch === email
? email
: paramsSearch === doc
? doc
: "";
If I understand it correctly, We have a search value and it should be match with either user.name, user.email or user.doc. If it will not match then we have to assign an empty string in the search.
You can achieve that in different ways :
const paramSearch = 'alpha';
const user = {
name: 'alpha',
email: 'alpha@gmail.com',
doc: 'document1',
}
const search = (paramSearch === user.name) ? user.name
: (paramSearch === user.email) ? user.email
: (paramSearch === user.doc) ? user.doc
: '';
console.log(search);
const paramSearch = 'alpha';
const user = {
name: 'alpha',
email: 'alpha@gmail.com',
doc: 'document1',
}
// Using Object.values() method to get the array of object values and then using Array.find() getting the matched element.
const search = Object.values(user).find(elem => elem === paramSearch)
// Using nullish operator to assign empty string if search is undefined or null
console.log(search ?? '')