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

173
Visualizações
How to loop through an array of object nth number of time so that it loop over all the child array of object if exist

How to loop through an array of object nth number of time so that it loop over all the child array of object if exist and get it's Id in order.

let = [{
  "id": "1",
  "child": [
    {
      "id": "12",
      "child": [
        {
          "id": "123",
          "child": [
           {
            "id": "1234"
           }
        }
      ]
    },
    {
      "id": "2",
      "child": [
        {
          "id": "22"
        }
      ]
    },
    {
      "id": "3"
    },
    {
      "id": "4",
      "child": [
        {

          "id": "42",
          "child": [
            {

              "id": "43"
            }
        }
      ]
    }
  ]
}]

Expected Output

[1,12,123,1234,2,22,3,4,42,43]

My try, It's not working and not getting any logic.

result.reduce((pv, cv) => {
  console.log(cv)

  let temp = cv
  let arr = []
  if(temp.hasOwnProperty("split")){
    arr = temp.split
    pv.push(temp.id)
    // again arr should loop, I'm still finding some logic!
  }
  return pv
}, [])

Kindly give some logical steps even if you won't like to answer. I'll try that!

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You need a recursive function with a persistent variable pointing to the array. .reduce isn't really the right approach here, and your test of temp.split doesn't make any sense - the two properties in question are id and child. Unconditionally push the ID (not inside the if), and if the child array exists, call the recursive function on it.

const input=[{id:"1",child:[{id:"12",child:[{id:"123",child:[{id:"1234"}]}]},{id:"2",child:[{id:"22"}]},{id:"3"},{id:"4",child:[{id:"42",child:[{id:"43"}]}]}]}];

const getAllChildIds = (arr, ids = []) => {
  for (const { id, child } of arr) {
    ids.push(Number(id));
    if (child) getAllChildIds(child, ids);
  }
  return ids;
};
console.log(getAllChildIds(input));

about 4 years ago · Santiago Trujillo 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