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

158
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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