Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
Ternary with three conditions Javascript

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You could try something like this.

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

about 4 years ago · Juan Pablo Isaza Report

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 ?? '')

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!