Nested List XML

by mtambulut

JavaScript

interface Options {
    value: string;
}

interface Item {
    id: number;
    options: Options[];
    children: Item[];
}

let hierarchy: Item;
let count = 0;

const createTreeView = (obj: any, parentItem: Item | null = null) => {
    const objRex = Object.entries(obj);
    
    for (let [key, value] of objRex) {
        count++;
        if (!parentItem) {
            parentItem = {
                id: count,
                options: [{ value: key }],
                children: []
            };
            hierarchy = parentItem;
            createTreeView(value, parentItem);
            break;
        }

        if (typeof (value) == 'string') {
            const item = { id: count, options: [{ value: "" + key.toString() + ' = ' + value }], children: [] } as Item;
            parentItem?.children.push(item);
        } else if (Array.isArray(value)) {
            const item = { id: count, options: [{ value: key }], children: [] } as Item;
            value.forEach(function (value, index, array) {
                createTreeView(value, item);
            });
            parentItem?.children.push(item);
        } else if (typeof (value) == 'object') {
            const item = { id: count, options: [{ value: key }], children: [] } as Item;
            createTreeView(value, item);
            parentItem?.children.push(item);
        }
    } 
}

/*
XML TO JSON

export const xmlToJson = (xml) => {
    var obj = {};
    
    if (xml.nodeType == 1) {
      if (xml.attributes.length > 0) {
        obj["@attributes"] = {};
        for (var j = 0; j < xml.attributes.length; j++) {
          var attribute = xml.attributes.item(j);
          obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
        }
      }
    } else if (xml.nodeType == 3) {
      obj = xml.nodeValue;
    }
  
    var textNodes = [].slice.call(xml.childNodes).filter(function(node) {
      return node.nodeType === 3;
    });
    if (xml.hasChildNodes() && xml.childNodes.length ===...