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

322
Visualizações
How to get a value of array of objects (pair key-value) in javascript?

Good time, i have an array of objects like this:

var sections = [ {key: 0, label: 'Nothing'}, {key: 11, label: 'Alex Right'},{key: 12, label: 'Dolores Black'},{key: 21, label: 'Bobby Smith'},{key: 26, label: 'Andrew Small'} ];

So, for example, i want to get label that is for key=12 (it have to be Dolores Black). If i use something like:

alert(sections[11]['label']);

this will be wrong, cause it will find 12th element of array, not an element with key=12. So what is th right expression for my case? Thanks

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

0

Use Array#find:

let sections = [ {key: 0, label: 'Nothing'}, {key: 11, label: 'Alex Right'},{key: 12, label: 'Dolores Black'},{key: 21, label: 'Bobby Smith'},{key: 26, label: 'Andrew Small'} ];
let res = sections.find(({key}) => key === 12)?.label;
console.log(res);

about 4 years ago · Juan Pablo Isaza Relatório

0

If you know that the element is nth in the array, use sections[n - 1]['label']; for example, to get Dolores Black (the 3rd element), you'd do:

sections[2]['label']; // 3 - 1 = 2

If you don't know the position of the element beforehand, you have to give some condition to JavaScript, so that it can find it; in your case, the condition is item.key === 12:

sections.find((item) => item.key === 12)['label'];

Note that in both cases we assume that the element actually exists in the array (if it doesn't, there will be errors).

about 4 years ago · Juan Pablo Isaza Relatório

0

I would wrap this in a function. Inside function i use the js function find(). If you have more items with the same id then i would use filter instead find.

const sections = [ {key: 0, label: 'Nothing'}, {key: 11, label: 'Alex Right'},{key: 12, label: 'Dolores Black'},{key: 21, label: 'Bobby Smith'},{key: 26, label: 'Andrew Small'} ];

const id = 11;

function getLabel(id) {
  return sections.find(e => e.key === id)['label'];
}
console.log(getLabel(id))

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