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

151
Vistas
Collect key value pair from array of objects Javascript

I have an array of objects in Javascript and I want to collect just the given key and value from the list. How would one do this? I feel like I have over engineered the solution but maybe not.

I wasn't sure if there was a cleaner way of doing this.

The results should be a list of objects containing just the key 'id' and id 'value'.

const items = [{
    id: "45054",
    name: "Brittany"
  },
  {
    id: "8980",
    name: "Amber"
  },
  {
    id: "9843",
    name: "Leslie"
  },
  {
    id: "45306",
    name: "Doug"
  },
  {
    id: "7863",
    name: "Kevin"
  },
]

let ids = []

for (let i = 0; i < items.length; i++) {
  ids.push({
    id: items[i].id
  })
}

console.log(ids)

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

that isn't bad, I personally would just use map:

let ids = items.map(item => ({id: item.id}));
about 4 years ago · Juan Pablo Isaza Denunciar

0

A cleaner way would be using Array.prototype.map(). Your answer is certainly not a wrong way to do so, though.

const items = [{
    id: "45054",
    name: "Brittany"
  },
  {
    id: "8980",
    name: "Amber"
  },
  {
    id: "9843",
    name: "Leslie"
  },
  {
    id: "45306",
    name: "Doug"
  },
  {
    id: "7863",
    name: "Kevin"
  },
]

const ids = items.map(x => ({id: x.id}));
console.log(ids)

about 4 years ago · Juan Pablo Isaza Denunciar

0

To deal with this you can use map like Pranev said, but if you want to have a more specific solution based on any other key, you can play with Object.keys, and then use the key that you want to get the id or any other key.

    const items = [
  {
    id: "45054",
    name: "Brittany",
  },
  {
    id: "8980",
    name: "Amber",
  },
  {
    id: "9843",
    name: "Leslie",
  },
  {
    id: "45306",
    name: "Doug",
  },
  {
    id: "7863",
    name: "Kevin",
  },
];

let ids = [];

for (let i = 0; i < items.length; i++) {
  const keys = Object.keys(items[i]);
  keys.forEach((key) => {
    if (key === "id") {
      ids.push({
        id: items[i][key],
      });
    }
  });
}
console.log(ids);
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