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
Pluck an object's properties and values into a new object

I want a nice small one liner to use an array, for example ['postcode','town'], and then pluck just these properties from a larger object.

So this:

const fields = ['postcode','town'];
const obj = {
    name: 'test',
    postcode: 'SS2 5JJ',
    town: 'Somewhere',
    other: 'info'
}

Would become this:

const filtered = {
    postcode: 'SS2 5JJ',
    town: 'Somewhere',
}

I did find this however I have mis-understood it I believe:

const fields = ['postcode','town'];
Object.keys(fields).map(e => fields[e])

What is the best way to do this?

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

0

You could use Array.reduce

const fields = ['postcode', 'town'];
const obj = {
  name: 'test',
  postcode: 'SS2 5JJ',
  town: 'Somewhere',
  other: 'info'
};

const filteredObj = fields.reduce((acc, cur) => Object.assign(acc, { [cur]: obj[cur] }), {});

console.log(filteredObj);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can map your array fields to [key, value] which will create an array of [key, value] pairs. Once you have this array, you can use Object.fromEntries() to build your object for each key-value pair:

const fields = ['postcode','town'];
const obj = { name: 'test', postcode: 'SS2 5JJ', town: 'Somewhere', other: 'info' };

const res = Object.fromEntries(fields.map(key => [key, obj[key]]));
console.log(res);

about 4 years ago · Juan Pablo Isaza Denunciar

0

"Best" is of course a subjective concept. But I think that the reduce function is the cleanest way of doing it. That way there is no need to chain together different functions.

const filtered = fields.reduce((prev, key) => ({[key]: obj[key], ...prev}), {});
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