Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

315
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda