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

162
Visualizações
How to determine whether an array object has a value, and then return the array of objects with this value

How to determine whether an array object has a value, and then return the array of objects with this value. Because I'm a novice, I tried to write it, but I didn't, give an example:

const menu = [
  {
    title: "one",
    children: [{name: "hello"}, {name: "bye"}],
  },{
    title: "two",
    children: [{name: "good"}, {name: "bad"}],
  },
]

Assume input "bad", the result should be:

menu = [
  {
    title: "two",
    children: [{name: "good"}, {name: "bad"}],
  }
]

How to do it?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Just loop through the array and then filter each element and its children like so:

const menu=[{title:"one",children:[{name:"hello",},{name:"bye",},],},{title:"two",children:[{name:"good",},{name:"bad"}]}];

const filterName = toFilter => {
  return menu.filter(({ children }) => {
    return children.some(({ name }) => name == toFilter);
  });
};

console.log(filterName("bad"));
console.log(filterName("good"));
console.log(filterName("neither"));
.as-console-wrapper { max-height: 100% !important; top: auto; }

about 4 years ago · Juan Pablo Isaza Relatório

0

As a beginner, don't get engaged with fancy Array methods and use simple loops. Try to use a for loop to loop over the menu array. Then for each item, loop over children property of the object. If name key matches with your desired output, you can push the whole object in your answer array:

const menu = [
      {
        title: "one",
        children: [
          {
            name: "hello",
          },
          {
            name: "bye",
          },
        ],
      },
      {
        title: "two",
        children: [
          {
            name: "good",
          },
          {
            name: "bad",
          },
        ],
      },
]
let ans = [];
for(let i = 0 ; i < menu.length;i++){
if(menu[i].children){
  for(let j = 0 ; j < menu[i].children.length; j++){
    if(menu[i].children[j].name === 'bad') ans.push(menu[i]);
  }
}
}

console.log(ans);

NOTE: The above assumes children is an array.

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