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

117
Visualizações
Filtering a nested array and return the array which matches the value for the key

I'm trying to filter an array which contains arrays of object, based on the id. I'm able to filter them, but need to clean up the output a bit as it also returns an empty array, since the condition doesn't match for that array.

How do I fix it?

const resKey = 'ABC';
const data = [
  [{
    "user": {
      "firstName": "John",
      "lastName": "Smith",
    },
    "id": "ABC"
  }],
  [{
    "user": {
      "firstName": "John",
      "lastName": "Smith",
    },
    "id": "DEF"
  }]
];

const result = data.map(eachArr => eachArr.filter(eachObj => eachObj.id === resKey));
console.log(result);

Expected Output:

[
  [
    {
      user: {
        firstName: "John",
        lastName: "Smith",
      },
      id: "ABC",
    },
  ],
]

Actual Output:

[
  [
    {
      user: {
        firstName: "John",
        lastName: "Smith",
      },
      id: "ABC",
    },
  ],
  [],
]
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can again filter out the empty array which doesn't contain an elements (length is 0) using filter.

.filter((arr) => arr.length);

const resKey = "ABC";
const data = [
  [
    {
      user: {
        firstName: "John",
        lastName: "Smith",
      },
      id: "ABC",
    },
  ],
  [
    {
      user: {
        firstName: "John",
        lastName: "Smith",
      },
      id: "DEF",
    },
  ],
];

const result = data
  .map((eachArr) => eachArr.filter((eachObj) => eachObj.id === resKey))
  .filter((arr) => arr.length);
  
console.log(result);

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