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

155
Visualizações
function to generate n length m depth data

I am trying to generate tree structure data, the problem is in helper function where I have an empty array children in which I want to push object with data, but get undefined

I do not get undefined when test it separately.

let b = {x: 1}
let a  = []
a.push(b)
console.log(a)

function forestMockDataGenerator(n, m) {
  const chance = new Chance(Math.random());
  const mock = Array.from(Array(n).keys());
  return mock.map(function (tree) {
    tree = {
      datum: chance.name(),
      children: [],
    };
    return helper(tree, 1);
    function helper(mock, count) {
      if (isCountNotEqualToM(count, m)) {
        mock.children.push({
          datum: equalOneAddressEqualTwoPhone(count),
          children: [],
        });
        helper(mock.children, (count = count + 1));
      }
      function equalOneAddressEqualTwoPhone(count) {
        return count === 1 ? chance.address() : chance.phone();
      }
      function isCountNotEqualToM(count, m) {
        return count !== m ? true : false;
      }
      return mock;
    }
  });
}

example 1

example 2

the data should have the next format

[
    {
      "name": "String",
      "children": [
        {
          "name": "String",
          "children": [
            // ...
          ]
        }, {
          "name": "String",
          "children": [
            // ...
          ]
        },
        // ...
      ]
    }, {
      "name": "String",
      "children": [
        // ...
      ]
    },
    // ...
  ]
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You yould use independent creation of children by handing over the decremented depth.

function forestMockDataGenerator(n, m) {
    if (!m) return [];
    return Array.from({ length: n }, (_, i) => ({
        name: `name${i}`,
        children: forestMockDataGenerator(n, m - 1),
    }));
}

console.log(forestMockDataGenerator(5, 3));
.as-console-wrapper { max-height: 100% !important; top: 0; }

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