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

112
Visualizações
Object hierarchy from XML document using JavaScript

Given an XML document such as this:

<Root> 
    <Child1>
        <ChildOfChild1_1> 
            <FinalChild> </FinalChild>
        </ChildOfChild1_1>
        <ChildOfChild1_2> </ChildOfChild1_2>
    </Child1>
    <Child2>
        <ChildOfChild2_1> </ChildOfChild2_1>
    </Child2>
    <Child3> </Child3>
</Root>

I would like to return a object which has only two parameters, name and children. It would look like:

{
    name: "Root"
    children: [
        {
            name: "Child1"
            children: [
                {
                    name: "ChildOfChild1_1"
                    children:[
                        {
                            name: "FinalChild"
                            children: null
                        }
                    ]
                },
                {
                    name: "ChildOfChild1_2"
                    children: null
                }

            ]
        }, 
        {
            name: "Child2"
            children: [
                {
                    name: "ChildOfChild2_1"
                    children: null
                }
            ]
        }, 
        {
            name: "Child3"
            children: null
        }, 
    ]
}

I do not care about node attributes, only nodeName and if they have children. I wrote code to get the first level of children but cannot wrap my head around the recursive part to get as deep as necessary. Thanks.

Below is what I have so far:

//assuming block is the root node and the root will at least have 1 child
let root = {
    name = '',
    children = []
};
root.name = block.nodeName;

for(let i=0 ; i<block.children.length ; i++) {
    root.children.push(getChildren(block.children[i]));
}

function getChildren(data) {
    let child = {};
    child.name = data.nodeName;
    child.children = []; //stuck here
    
    return child;
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The task is much simpler than you think.

You want a function that returns a node name and the list of node children, each of them processed in the exact same way:

function toObject(node) {
    return {
        name: node.nodeName,
        children: [...node.children].map(toObject)
    };
}

That's it.

const xmlDoc = new DOMParser().parseFromString(`<Root> 
    <Child1>
        <ChildOfChild1_1> 
            <FinalChild> </FinalChild>
        </ChildOfChild1_1>
        <ChildOfChild1_2> </ChildOfChild1_2>
    </Child1>
    <Child2>
        <ChildOfChild2_1> </ChildOfChild2_1>
    </Child2>
    <Child3> </Child3>
</Root>
`, "application/xml");

function toObject(node) {
    return {
        name: node.nodeName,
        children: [...node.children].map(toObject)
    };
}

const tree = toObject(xmlDoc.documentElement);
console.log(tree);

If you really want null when there are no children (an empty array is much easier to handle down the line, trust me), I'm sure you can make the necessary change in toObject yourself.

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