У меня есть XML-данные, которые мне нужно преобразовать в массив, XML-данные имеют иерархию, но они находятся на том же уровне, следовательно, проблему идентифицировать. Я дал ожидаемый выходной массив ниже вместе с моей работой.

Эти следующие данные XML могут иметь несколько иерархий

{amp}lt;data{amp}gt; {amp}lt;GROUP NAME="Sundry Debtors"{amp}gt; {amp}lt;PARENT{amp}gt;{amp}lt;/PARENT{amp}gt; {amp}lt;/GROUP{amp}gt; {amp}lt;GROUP NAME="Sundry Debtors-Pune"{amp}gt; {amp}lt;PARENT{amp}gt;Sundry Debtors{amp}lt;/PARENT{amp}gt; {amp}lt;/GROUP{amp}gt; {amp}lt;GROUP NAME="Sundry Debtors-Akurdi"{amp}gt; {amp}lt;PARENT{amp}gt;Sundry Debtors-Pune{amp}lt;/PARENT{amp}gt; {amp}lt;/GROUP{amp}gt; {amp}lt;GROUP NAME="Sundry Creditors"{amp}gt; {amp}lt;PARENT{amp}gt;{amp}lt;/PARENT{amp}gt; {amp}lt;/GROUP{amp}gt; {amp}lt;GROUP NAME="Sundry Creditors-Pune"{amp}gt; {amp}lt;PARENT{amp}gt;Sundry Creditors{amp}lt;/PARENT{amp}gt; {amp}lt;/GROUP{amp}gt; {amp}lt;/data{amp}gt; 

Ниже приведен ожидаемый вывод из вышеуказанных данных XML

 let arr = [ { name: "Sundry Debtors", data: [{ name: "Sundry Debtors-Pune", data: [{ name: "Sundry Debtors-Akurdi", data: [] }] }] }, { name: "Sundry Creditors", data: [{ name: "Sundry Creditors-Pune", data: [] }] } ]; 

Вот что я пробовал до сих пор

 {amp}lt;!DOCTYPE html{amp}gt; {amp}lt;html{amp}gt; {amp}lt;title{amp}gt;test{amp}lt;/title{amp}gt; {amp}lt;script{amp}gt; //Desired output let arr = [ { name: "Sundry Debtors", data: [{ name: "Sundry Debtors-Pune", data: [{ name: "Sundry Debtors-Akurdi", data: [] }] }] }, { name: "Sundry Creditors", data: [{ name: "Sundry Creditors-Pune", data: [] }] } ]; let text = '{amp}lt;data{amp}gt;{amp}lt;GROUP NAME="Sundry Debtors"{amp}gt;{amp}lt;PARENT{amp}gt;{amp}lt;/PARENT{amp}gt;{amp}lt;/GROUP{amp}gt;{amp}lt;GROUP NAME="Sundry Debtors-Pune"{amp}gt;{amp}lt;PARENT{amp}gt;Sundry Debtors{amp}lt;/PARENT{amp}gt;{amp}lt;/GROUP{amp}gt;{amp}lt;GROUP NAME="Sundry Debtors-Akurdi"{amp}gt;{amp}lt;PARENT{amp}gt;Sundry Debtors-Pune{amp}lt;/PARENT{amp}gt;{amp}lt;/GROUP{amp}gt;{amp}lt;GROUP NAME="Sundry Creditors"{amp}gt;{amp}lt;PARENT{amp}gt;{amp}lt;/PARENT{amp}gt;{amp}lt;/GROUP{amp}gt;{amp}lt;GROUP NAME="Sundry Creditors-Pune"{amp}gt;{amp}lt;PARENT{amp}gt;Sundry Creditors{amp}lt;/PARENT{amp}gt;{amp}lt;/GROUP{amp}gt;{amp}lt;/data{amp}gt;'; let parser = new DOMParser(); let xml = parser.parseFromString(text, "text/xml"); var node = xml.getElementsByTagName("GROUP"); let total = 0; let levels = []; let level = 0; let hirarchy = []; total = node.length; function getChilds(parent) { let arr = []; for (let j = 0; j {amp}lt; total; j  ) { let e = node[j]; let grpName = e.getAttribute("NAME"); let parentCount = e.getElementsByTagName("PARENT")[0].childNodes.length; if (parentCount {amp}gt; 0) { let parentName = e.getElementsByTagName("PARENT")[0].childNodes[0].nodeValue; if (parentName === parent) { arr.push(grpName); } } } return arr; } function getParent(child) { let arr = []; for (let k = 0; k {amp}lt; total; k  ) { let e = node[k]; let grpName = e.getAttribute("NAME"); if (grpName === child) { let parentCount = e.getElementsByTagName("PARENT")[0].childNodes.length; let parentName = parentCount {amp}gt; 0 ? e.getElementsByTagName("PARENT")[0].childNodes[0].nodeValue : undefined; return parentName; } } } function findNode(array, nodename) { for (let j = 0; j {amp}lt; array.length; j  ) { const e = array[j]; if (e.name === nodename) { return e; } else { if (e.data.length {amp}gt; 0) { //console.log(e.data, nodename); return findNode(e.data, nodename); } else { return null; } } } } let new_h = []; for (i = 0; i {amp}lt; total; i  ) { let e = node[i]; let grpName = e.getAttribute("NAME"); let childs = getChilds(grpName); let parent = getParent(grpName); //console.log(i, grpName, " ---{amp}gt;", childs, parent); if (!parent) { let arr = { name: grpName, data: [] }; new_h.push(arr); } else { let arr = findNode(new_h, parent); if (arr) { arr.data.push({ name: grpName, data: [] }); } else { } } } console.log(new_h); {amp}lt;/script{amp}gt; {amp}lt;/html{amp}gt; 

Попробуйте следующий код.

 {amp}lt;!DOCTYPE html{amp}gt; {amp}lt;html{amp}gt; {amp}lt;title{amp}gt;test{amp}lt;/title{amp}gt; {amp}lt;script{amp}gt; let expected_output_array = [ { name: "Sundry Debtors", data: [{ name: "Sundry Debtors-Pune", data: [{ name: "Sundry Debtors-Akurdi", data: [] }] }] }, { name: "Sundry Creditors", data: [{ name: "Sundry Creditors-Pune", data: [] }] } ]; let text = '{amp}lt;data{amp}gt;{amp}lt;GROUP NAME="Sundry Debtors"{amp}gt;{amp}lt;PARENT{amp}gt;{amp}lt;/PARENT{amp}gt;{amp}lt;/GROUP{amp}gt;{amp}lt;GROUP NAME="Sundry Debtors-Pune"{amp}gt;{amp}lt;PARENT{amp}gt;Sundry Debtors{amp}lt;/PARENT{amp}gt;{amp}lt;/GROUP{amp}gt;{amp}lt;GROUP NAME="Sundry Debtors-Akurdi"{amp}gt;{amp}lt;PARENT{amp}gt;Sundry Debtors-Pune{amp}lt;/PARENT{amp}gt;{amp}lt;/GROUP{amp}gt;{amp}lt;GROUP NAME="Sundry Creditors"{amp}gt;{amp}lt;PARENT{amp}gt;{amp}lt;/PARENT{amp}gt;{amp}lt;/GROUP{amp}gt;{amp}lt;GROUP NAME="Sundry Creditors-Pune"{amp}gt;{amp}lt;PARENT{amp}gt;Sundry Creditors{amp}lt;/PARENT{amp}gt;{amp}lt;/GROUP{amp}gt;{amp}lt;/data{amp}gt;'; let parser = new DOMParser(); let xml = parser.parseFromString(text, "text/xml"); var node = xml.getElementsByTagName("GROUP"); let total = 0; total = node.length; function getChilds(parent) { let arr = []; for (let j = 0; j {amp}lt; total; j  ) { let e = node[j]; let grpName = e.getAttribute("NAME"); let parentCount = e.getElementsByTagName("PARENT")[0].childNodes.length; if (parentCount {amp}gt; 0) { let parentName = e.getElementsByTagName("PARENT")[0].childNodes[0].nodeValue; if (parentName === parent) { arr.push(grpName); } } } return arr; } function getParent(child) { let arr = []; let total = node.length; for (let k = 0; k {amp}lt; total; k  ) { let e = node[k]; let grpName = e.getAttribute("NAME"); if (grpName === child) { let parentCount = e.getElementsByTagName("PARENT")[0].childNodes.length; let parentName = parentCount {amp}gt; 0 ? e.getElementsByTagName("PARENT")[0].childNodes[0].nodeValue : undefined; return parentName; } } } function findNodeSequential(array, nodename) { for (let k = 0; k {amp}lt; array.length; k  ) { const e = array[k]; if (e.name === nodename) { return e; } else { if (e.data.length {amp}gt; 0) { return findNodeSequential(e.data, nodename); } else { return null; } } } } function findNode(array, nodename) { for (let j = 0; j {amp}lt; array.length; j  ) { let e = array[j]; if (e.name === nodename) { return e; } else { if (e.data.length {amp}gt; 0) { e = findNodeSequential(e.data, nodename); if (e !== null) { return e; } } } } } let h = []; for (let i = 0; i {amp}lt; total; i  ) { let e = node[i]; let grpName = e.getAttribute("NAME"); let childs = getChilds(grpName); let parent = getParent(grpName); if (!parent) { let arr = { name: grpName, data: [] }; h.push(arr); } } for (let l = 0; l {amp}lt; total; l  ) { let e = node[l]; let grpName = e.getAttribute("NAME"); let childs = getChilds(grpName); let parent = getParent(grpName); if (parent) { let arr = findNode(h, parent); if (arr) { arr.data.push({ name: grpName, data: [] }); } else { } } } console.log("Expected output:", expected_output_array); console.log("Output: ", h); {amp}lt;/script{amp}gt; {amp}lt;/html{amp}gt; 

Сушант Кадам

новый участник этого сайта. Будьте внимательны, спрашивая разъяснения, комментируя и отвечая. Проверьте наш

Правила поведения

,

Надеюсь, это поможет,

 var convert = require('xml-js'); let xmlString = `{amp}lt;?xml version="1.0" encoding="UTF-8"?{amp}gt; {amp}lt;data{amp}gt; {amp}lt;GROUP NAME="Sundry Debtors"{amp}gt; {amp}lt;PARENT{amp}gt;{amp}lt;/PARENT{amp}gt; {amp}lt;/GROUP{amp}gt; {amp}lt;GROUP NAME="Sundry Debtors-Pune"{amp}gt; {amp}lt;PARENT{amp}gt;Sundry Debtors{amp}lt;/PARENT{amp}gt; {amp}lt;/GROUP{amp}gt; {amp}lt;GROUP NAME="Sundry Debtors-Akurdi"{amp}gt; {amp}lt;PARENT{amp}gt;Sundry Debtors-Pune{amp}lt;/PARENT{amp}gt; {amp}lt;/GROUP{amp}gt; {amp}lt;GROUP NAME="Sundry Creditors"{amp}gt; {amp}lt;PARENT{amp}gt;{amp}lt;/PARENT{amp}gt; {amp}lt;/GROUP{amp}gt; {amp}lt;GROUP NAME="Sundry Creditors-Pune"{amp}gt; {amp}lt;PARENT{amp}gt;Sundry Creditors{amp}lt;/PARENT{amp}gt; {amp}lt;/GROUP{amp}gt; {amp}lt;/data{amp}gt;`; /* convert xml to json object */ result = convert.xml2js(xmlString, {compact: true, spaces: 4}); let exists_arr = []; var group = result.data.GROUP; function fchild(par) { let final = []; for (var i = 0; i {amp}lt;= group.length - 1; i  ) { let {_attributes, PARENT} = group[i]; /* checking if its the top-most level group (Object.keys(PARENT).length == 0 then its top level group) and does not exist in exists_arr */ if( Object.keys(PARENT).length == 0 {amp}amp;{amp}amp; par == false {amp}amp;{amp}amp; !exists_arr.includes(_attributes.NAME)){ /* push to exists_arr */ exists_arr.push(_attributes.NAME); /* push to final array, also calling the function in recurtion to find the children of the current */ final.push({ name:_attributes.NAME, data:fchild(_attributes.NAME)}); } else if(par == PARENT._text {amp}amp;{amp}amp; !exists_arr.includes(_attributes.NAME) ){ /* entering if 'par' value matches with parent text {amp}amp; does not exist in exists_arr */ /* push to exists_arr */ exists_arr.push(_attributes.NAME); /* push to final array, also calling the function in recurtion */ final.push({ name:_attributes.NAME, data:fchild(_attributes.NAME)}); } } return final; } console.log(JSON.stringify(fchild(false))); 
Вайбхав П

новый участник этого сайта. Будьте внимательны, спрашивая разъяснения, комментируя и отвечая. Проверьте наш

Правила поведения

,