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

241
Visualizações
Return values from Obj if key in Array

I'm still learning basics of map(), filter(), forEach(), and includes() and can't seem to figure out the best way or anyway of attempting this...

Let's say I've got an arr and an obj and I need to return the object values if object key is in the array

const array = [1, 2, 3];

const object = { 1: "blue", 2: "red", 3: "green", 4: "orange", 5: "purple" };

I believe because I'm going for a new array, I need to use map()

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

0

You can use Object.entries(object) to get an array of key value pairs of the object, then filter according to the array elements, finally map and return only the values:

const array = [1, 2, 3];

const object = { 1: "blue", 2: "red", 3: "green", 4: "orange", 5: "purple" };

const result = Object.entries(object).filter(el=>array.includes(parseInt(el[0]))).map(el=>el[1])

console.log(result)

Or if you want to keep the order order of the elements (thanks to ASDFGerte), just map over the array and return the value of the element.

const array = [3,2,1];
const object = { 1: "blue", 2: "red", 3: "green", 4: "orange", 5: "purple" };

const result = array.map(el => object[el]);

console.log(result)

about 4 years ago · Juan Pablo Isaza Relatório

0

We will only be returning values with keys that are present in the array. So you can simply iterate through the array values, and check if there is a value in the object with the array value as the key. Since you want it to return the values from the call itself maybe we can use reduce:

let values = array.reduce((found, item) => {
    return (item in object) ? found.push(object[item]) && found : found
}, [])
console.log(values)
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