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

104
Vistas
Filter an array of objects according to the name of the key in the objects

I have an array of objects that I want to filter based on the name of the key for those objects. In this particular case I know that there will be one key/value pair for each element in the array.

Assume an array that looks like this:

let dataArray = [
  {
    "name": "David" 
  },
  {
    "location": "New York"
  },
  {
    "name": "Jenna"
  }
]

What I want to end up with is just an array where the key is 'name':

[
  {
    name: "David" 
  },
  {
    name: "Jenna"
  }
]

I've tried various ways of doing this using the filter method, such as this:

const namesArr = dataArr.filter(i => i[key] === 'name');

But none seem to produce the correct result.

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

0

Use the in operator to check if a property exists on the object:

const dataArray = [{"name":"David"},{"location":"New York"},{"name":"Jenna"}];

// name exists on the object
console.log(dataArray.filter(item => 'name' in item));

// or location doesn't exist on the object
console.log(dataArray.filter(item => !('location' in item)));

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use the in operator to filter on a particular key being present, see reference.

dataArr.filter(obj => 'name' in obj)

Only checking obj.name would exclude objects where 'name' field is false or null or undefined, even if the property is present on the object.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use the object.hasOwnProperty('name') that returns a boolean indicating whether object has a property name

let dataArray = [
  {
    "name": "David" 
  },
  {
    "location": "New York"
  },
  {
    "name": "Jenna"
  }
]

const filtered = dataArray.filter(x => x.hasOwnProperty('name'));

console.log(filtered);

another option is to use the in operator:

let dataArray = [
  {
    "name": "David" 
  },
  {
    "location": "New York"
  },
  {
    "name": "Jenna"
  }
]

const filtered = dataArray.filter(x => 'name' in x);

console.log(filtered);

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