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

147
Vistas
Filter an object based on values in an array

I have an object that contains people's names and ages

{"John":44,"Sarah":23,"Bob":43,"Kate":65,"Bill":18}

and an array that provides a list of employee names

['John', 'Bob', 'Kate', 'Bill', 'Fred']

I would like to create a new object which contains only those people and their ages that appear in both the object and array. So in this example the new object would contain

{"John":44,"Bob":43,"Kate":65,"Bill":18}

"Sarah":23 and Fred don't appear because they appear in only one of the above.

Can anyone advise on how to do this please?

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

0

You can use reduce to create the result and operator in to check if the key exists:

const obj = {"John":44,"Sarah":23,"Bob":43,"Kate":65,"Bill":18};
const keys = ['John', 'Bob', 'Kate', 'Bill', 'Fred'];

const result = keys.reduce((acc, el) => {
  if (el in obj) acc[el] = obj[el];
  return acc;
}, {});

console.log(result);

Another approach is to convert the object to an array, use filter and convert the result back:

const obj = {"John":44,"Sarah":23,"Bob":43,"Kate":65,"Bill":18};
const keys = ['John', 'Bob', 'Kate', 'Bill', 'Fred'];

const result = Object.fromEntries(Object.entries(obj).filter(([key]) => keys.includes(key)));

console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar

0

simply

const 
  jso = { John: 44, Sarah: 23, Bob: 43, Kate: 65, Bill: 18 } 
, arr = [ 'John', 'Bob', 'Kate', 'Bill', 'Fred' ]
, res = arr.reduce((r,a)=>(!!jso[a]?r[a]=jso[a]:'',r),{})
  ;
console.log(res)

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