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

148
Visualizações
Transform data structure to tree data in JavaScript

I have a data structure like this:

 data = [
    {
      parent: {name: 'Sheet'},
      firstArray: [{sampleVar: 0.3, typeName: 'active'}, {sampleVar: 0.4, typeName: 'active'}],
      secondArray: [{sampleVar: 1.2, typeName: 'passive'}, {sampleVar: 1.3 , typeName: 'passive'}]
    },...
  ]

I want to transform it to a tree data like this:

  treeData = [
    {
      parent: {
        name: 'Sheet',
        children: [{
          typeName: 'active',
          children: [
            {sampleVar: 0.3},
            {sampleVar: 0.4}
          ]
        },
          {
            typeName: 'passive',
            children: [
              {sampleVar: 1.2},
              {sampleVar: 1.3}
            ]
          },...
        ]
      },...
    }
  ];

I have to mention that my variable typeName has the same value for each array. Does anyone know a good approach to achieve this?

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

0

You can use Object.values and map to get the result. I've used an example input that varies a bit more:

const data = [{
  parent: {name: 'SheetA'},
  justOne: [{sampleVar: 0.3, typeName: 'active'}],
  hasTwo: [{indicator: 1.2, typeName: 'passive'}, {indicator: 1.3 , typeName: 'passive'}]
}, {
  parent: {name: 'SheetB'},
  hasThree: [{otherVar: 9.3, typeName: 'selected'}, {otherVar: 9.4, typeName: 'selected'}, {otherVar: 9.5, typeName: 'selected'}],
  secondArray: [{message: 7.2, typeName: 'locked'}, {message: 7.3 , typeName: 'locked'}]
}];

const treeData = data.map(({parent, ...rest}) => ({
    ...parent,
    children: Object.values(rest).map(arr => ({
        typeName: arr[0]?.typeName,
        children: arr.map(({typeName, ...rest}) => rest)
    }))
}));

console.log(treeData);

about 4 years ago · Juan Pablo Isaza Relatório

0

Considering each array has 2 items only each array has its own typename this works.

var result = [
    {
        parent: {
            name: data[0].parent.name,
            children: []
        }
    }
];

for (const property in data[0]) {
    if (property == "parent") continue;
    let array = data[0][property];
    result[0].parent.children.push({
        typeName: array[0].typeName,
        children: [
            {
                sampleVar: array[0].sampleVar
            },
            {
                sampleVar: array[1].sampleVar
            }
        ]
    });
}

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