Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

414
Visualizações
Javascript object declaration with ternary operator

I'm declaring an object inside one of my components like below:

const data = {
        user: id,
        userRole: role,
        teacherdepartment: department
}

But now I wanted to do this declaration dynamically depends on a specific value, like below:

let usertype='teacher';
const data = {
        user: id,
        userRole: role,
        if(usertype=='teacher'?(teacherdepartment:tdepartment):(studentDepartment:sdepartment))
}

Is this possible. I know I can do it with nested ternary operator. But inside the object structure any simple line that can do that trick?

Update: object values can be easily set using ternary inside the object declaration, but this is for object key so this is not a duplicate of this. Also, in the above example I have put a simple object. Image if the objects have some child and ternary conditions within.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Try with conditional operator for both key and value. Keys can be made dynamic by adding [] around the key expression.

Pseude Code

const data = {
    user: id,
    userRole: role,
    [usertype=='teacher'? 'teacherdepartment' : 'studentDepartment']: usertype=='teacher'? tdepartment: sdepartment,
}

Working Code

const usertype = 'student';
const tdepartment = 'tdepartment';
const sdepartment = 'sdepartment';
const id = 'id';
const role = 'role';
const data = {
  user: id,
  userRole: role,
  [usertype=='teacher'? 'teacherdepartment' : 'studentDepartment']: usertype=='teacher'? tdepartment: sdepartment,
};
console.log(data)

about 4 years ago · Juan Pablo Isaza Relatório

0

I'd avoid a ternary operator altogether because they're confusing to read in a lot of situations. Instead I would create a dictionary that maps user types to string values, and then create the property dynamically with that information.

const userType = 'teacher';

const dict = { teacher: 'tdepartment', student: 'sdepartment' };

const data = {
  user: 'id',
  userRole: 'role',
  [`${userType}Department`]: dict[userType]
}

console.log(data);

about 4 years ago · Juan Pablo Isaza Relatório

0

I think this could be refactored into

let usertype = 'teacher';

let departmentProperty = usertype === 'teacher' ? 'teacherdepartment' : 'studentDepartment';
let departmentValue = usertype === 'teacher' ? 'teacherdepartmentValue' : 'studentDepartment';
const data = {
    user: 'id',
    userRole: 'role',
    [departmentProperty]: departmentValue,
};

console.log(data)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda