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

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

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 Denunciar

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