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

167
Visualizações
Filtering nested objects via Attribute with Javascript-

I have an array of nested objects, I want to filter this to return only the object tjat contains an author who's age === 21.

I've attempted to implement this SO answer, but I keep having 'x is not a function' returned.

let arrayOfElements = 
[
  {
  author: { name: 'Kim', age: 21 },
  employment: { employer: 'Logiothech', role: 'Human Resources' }
  }
  
  {
  author: { name: 'John', age: 62 },
  employment: { employer: 'Logiothech', role: 'Human Resources' }
  }
  
  {
  author: { name: 'Mary', age: 31 },
  employment: { employer: 'Logiothech', role: 'Human Resources' }
  }
  
];

What I have tried: (I believe I'm incorrectly using subElements, but unsure what to correctly sub in it's place)

 let filteredMap =  array_of_elements.map((element) => {
return {...element, subElements: element.subElements.filter((subElement) => subElement.author.age === 21)}
})
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You just need the .filter array method. the .map method is when you want to make a change to each element in the array. Here is what I came up with:

let filteredArray = arrayOfElements.filter((element) => element.author.age == 21)

Full code:

let arrayOfElements = 
[
  {
  author: { name: 'Kim', age: 21 },
  employment: { employer: 'Logiothech', role: 'Human Resources' }
  },
  
  {
  author: { name: 'John', age: 62 },
  employment: { employer: 'Logiothech', role: 'Human Resources' }
  },
  
  {
  author: { name: 'Mary', age: 31 },
  employment: { employer: 'Logiothech', role: 'Human Resources' }
  }
  
];

let filteredArray = arrayOfElements.filter((element) => element.author.age == 21)

console.log(filteredArray)

about 4 years ago · Juan Pablo Isaza Relatório

0

I could be wrong, but it looks like you're overthinking it a bit. Try this:

arrayOfElements.filter(element => element.author.age === 21);

This will return an array of objects (in this case one) that have an author whose age is 21.

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