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

106
Visualizações
Get object property name with corresponding value

I have a field object that can contain only one of different properties with an id as a value.

const Field = {
  // Field can contain
  property1Id: 'someId',
  // Or 
  property2Id: 'someOtherId',
  // Or
  property3Id: '...'
  //...
};

I want to return the property name and it's value. The following works fine but feels a bit long. Anyway to reduce it / be more efficient.

const propertyName = Field.property1Id
  ? 'Property 1'
  : someObject.property2Id
  ? 'Property 2'
  : someObject.property3Id
  ? 'Property 3'
  : 'Other';

const id = Field.object1Id
  ? Field.property1Id
  : Field.property2Id
  ? Field.property2Id
  : Field.property3Id
  ? Field.property3Id
  : null;

console.log(propertyName, id)

Thanks.

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

0

If this is what you mean, every property name with property value is returned :)

const Field = {
   // Field can contain
  property1Id: 'someId',
  // Or 
  property2Id: 'someOtherId',
  // Or
  property3Id: '...'
  //...
}

let entries = Object.entries(Field);
entries.forEach(entry => {
  console.log(entry)
})

about 4 years ago · Juan Pablo Isaza Relatório

0

Best approach

const Field = {
  // Field can contain
  property1Id: 'someId',
  // Or 
  property2Id: 'someOtherId',
  // Or
  property3Id: '...'
  //...
};

let i = 0;
for (const property in Field) {
  i++
  console.log('Property ' + i, Field[property]);
}

Output: 
"Property 1" "someId"
"Property 2" "someOtherId"
"Property 3" "..."
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