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

106
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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