-2

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

Amanda
  • 1
  • 3
  • 1
    Do you really mean _“if its equal to name, email **and** doc”_ instead of _“if its equal to name, email **or** doc”_? See [Check variable equality against a list of values](/q/4728144/4642212). How is this specifically about the conditional operator? – Sebastian Simon Mar 25 '22 at 01:59
  • I'm gonna change it its actually if its either equal to one of them so it would be an OR case – Amanda Mar 25 '22 at 02:00
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Mar 25 '22 at 06:58
  • @Amanda I added an answer with 2 solutions. I hope that will help in your requirement. – Debug Diva Mar 25 '22 at 11:13

2 Answers2

0

You could try something like this.

const search =
  paramsSearch === name
    ? name
    : paramsSearch === email
    ? email
    : paramsSearch === doc
    ? doc
    : "";

Kundan
  • 1,754
  • 16
  • 37
0

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 :

  1. Using nested ternary operators.

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);
  1. We can achieve it by using Array.find() method of JavaScript.

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 ?? '')
Debug Diva
  • 26,058
  • 13
  • 70
  • 123