我有一个复杂的json文件,我必须处理javascript使其分层,以便稍后构建树。 json的每个条目都有: Id:唯一的Id, parentId:父节点的id(如果节点是树的根,则为0) Level:树的深度级别

json数据已经“有序”。我的意思是,一个条目在它上面有一个父节点或兄弟节点,在它下面有一个子节点或兄弟节点。

输入:

{
    "People": [
        {
            "id": "12",
            "parentId": "0",
            "text": "Man",
            "level": "1",
            "children": null
        },
        {
            "id": "6",
            "parentId": "12",
            "text": "Boy",
            "level": "2",
            "children": null
        },
                {
            "id": "7",
            "parentId": "12",
            "text": "Other",
            "level": "2",
            "children": null
        },
        {
            "id": "9",
            "parentId": "0",
            "text": "Woman",
            "level": "1",
            "children": null
        },
        {
            "id": "11",
            "parentId": "9",
            "text": "Girl",
            "level": "2",
            "children": null
        }
    ],
    "Animals": [
        {
            "id": "5",
            "parentId": "0",
            "text": "Dog",
            "level": "1",
            "children": null
        },
        {
            "id": "8",
            "parentId": "5",
            "text": "Puppy",
            "level": "2",
            "children": null
        },
        {
            "id": "10",
            "parentId": "13",
            "text": "Cat",
            "level": "1",
            "children": null
        },
        {
            "id": "14",
            "parentId": "13",
            "text": "Kitten",
            "level": "2",
            "children": null
        },
    ]
}

预期产量:

{
    "People": [
        {
            "id": "12",
            "parentId": "0",
            "text": "Man",
            "level": "1",
            "children": [
                {
                    "id": "6",
                    "parentId": "12",
                    "text": "Boy",
                    "level": "2",
                    "children": null
                },
                {
                    "id": "7",
                    "parentId": "12",
                    "text": "Other",
                    "level": "2",
                    "children": null
                }   
            ]
        },
        {
            "id": "9",
            "parentId": "0",
            "text": "Woman",
            "level": "1",
            "children":
            {

                "id": "11",
                "parentId": "9",
                "text": "Girl",
                "level": "2",
                "children": null
            }
        }

    ],    

    "Animals": [
        {
            "id": "5",
            "parentId": "0",
            "text": "Dog",
            "level": "1",
            "children": 
                {
                    "id": "8",
                    "parentId": "5",
                    "text": "Puppy",
                    "level": "2",
                    "children": null
                }
        },
        {
            "id": "10",
            "parentId": "13",
            "text": "Cat",
            "level": "1",
            "children": 
            {
                "id": "14",
                "parentId": "13",
                "text": "Kitten",
                "level": "2",
                "children": null
            }
        }

    ]
}

当前回答

你可以使用npm包数组到树https://github.com/alferov/array-to-tree。 它将普通的节点数组(带有指向父节点的指针)转换为嵌套的数据结构。

解决了从数据库数据集检索到嵌套数据结构(即导航树)的转换问题。

用法:

var arrayToTree = require('array-to-tree');

var dataOne = [
  {
    id: 1,
    name: 'Portfolio',
    parent_id: undefined
  },
  {
    id: 2,
    name: 'Web Development',
    parent_id: 1
  },
  {
    id: 3,
    name: 'Recent Works',
    parent_id: 2
  },
  {
    id: 4,
    name: 'About Me',
    parent_id: undefined
  }
];

arrayToTree(dataOne);

/*
 * Output:
 *
 * Portfolio
 *   Web Development
 *     Recent Works
 * About Me
 */

其他回答

以防有家长需要。参考id 2,它有多个父元素

const dataSet = [{ "ID": 1, "Phone": "(403) 125-2552", "City": "Coevorden", "Name": "Grady" }, {"ID": 2, "Phone": "(403) 125-2552", "City": "Coevorden", "Name": "Grady" }, { "ID": 3, "parentID": [1,2], "Phone": "(979) 486-1932", "City": "Chełm", "Name": "Scarlet" }]; const expectedDataTree = [ { "ID":1, "Phone":"(403) 125-2552", "City":"Coevorden", "Name":"Grady", "childNodes":[{ "ID":2, "parentID":[1,3], "Phone":"(979) 486-1932", "City":"Chełm", "Name":"Scarlet", "childNodes":[] }] }, { "ID":3, "parentID":[], "Phone":"(403) 125-2552", "City":"Coevorden", "Name":"Grady", "childNodes":[ { "ID":2, "parentID":[1,3], "Phone":"(979) 486-1932", "City":"Chełm", "Name":"Scarlet", "childNodes":[] } ] } ]; const createDataTree = dataset => { const hashTable = Object.create(null); dataset.forEach(aData => hashTable[aData.ID] = {...aData, childNodes: []}); const dataTree = []; dataset.forEach(Datae => { if (Datae.parentID && Datae.parentID.length > 0) { Datae.parentID.forEach( aData => { hashTable[aData].childNodes.push(hashTable[Datae.ID]) }); } else{ dataTree.push(hashTable[Datae.ID]) } }); return dataTree; }; window.alert(JSON.stringify(createDataTree(dataSet)));

将节点数组转换为树

ES6函数转换数组节点(由父ID相关)到树结构:

/**
 * Convert nodes list related by parent ID - to tree.
 * @syntax getTree(nodesArray [, rootID [, propertyName]])
 *
 * @param {Array} arr   Array of nodes
 * @param {integer} id  Defaults to 0
 * @param {string} p    Property name. Defaults to "parent_id"
 * @returns {Object}    Nodes tree
 */

const getTree = (arr, p = "parent_id") => arr.reduce((o, n) => {

  if (!o[n.id]) o[n.id] = {};
  if (!o[n[p]]) o[n[p]] = {};
  if (!o[n[p]].nodes) o[n[p]].nodes= [];
  if (o[n.id].nodes) n.nodes= o[n.id].nodes;

  o[n[p]].nodes.push(n);
  o[n.id] = n;

  return o;
}, {});

从节点树生成HTML列表

有了我们的树,这里有一个递归函数来构建UL > LI元素:

/**
 * Convert Tree structure to UL>LI and append to Element
 * @syntax getTree(treeArray [, TargetElement [, onLICreatedCallback ]])
 *
 * @param {Array} tree Tree array of nodes
 * @param {Element} el HTMLElement to insert into
 * @param {function} cb Callback function called on every LI creation
 */

const treeToHTML = (tree, el, cb) => el.append(tree.reduce((ul, n) => {
  const li = document.createElement('li');

  if (cb) cb.call(li, n);
  if (n.nodes?.length) treeToHTML(n.nodes, li, cb);

  ul.append(li);
  return ul;
}, document.createElement('ul')));

演示时间

下面是一个使用上述两个函数的线性节点数组的例子:

const getTree = (arr, p = "parent_id") => arr.reduce((o, n) => { if (!o[n.id]) o[n.id] = {}; if (!o[n[p]]) o[n[p]] = {}; if (!o[n[p]].nodes) o[n[p]].nodes = []; if (o[n.id].nodes) n.nodes = o[n.id].nodes; o[n[p]].nodes.push(n); o[n.id] = n; return o; }, {}); const treeToHTML = (tree, el, cb) => el.append(tree.reduce((ul, n) => { const li = document.createElement('li'); if (cb) cb.call(li, n); if (n.nodes?.length) treeToHTML(n.nodes, li, cb); ul.append(li); return ul; }, document.createElement('ul'))); // DEMO TIME: const nodesList = [ {id: 10, parent_id: 4, text: "Item 10"}, // PS: Order does not matters {id: 1, parent_id: 0, text: "Item 1"}, {id: 4, parent_id: 0, text: "Item 4"}, {id: 3, parent_id: 5, text: "Item 3"}, {id: 5, parent_id: 4, text: "Item 5"}, {id: 2, parent_id: 1, text: "Item 2"}, ]; const myTree = getTree(nodesList)[0].nodes; // Get nodes of Root (0) treeToHTML(myTree, document.querySelector("#tree"), function(node) { this.textContent = `(${node.parent_id} ${node.id}) ${node.text}`; this._node = node; this.addEventListener('click', clickHandler); }); function clickHandler(ev) { if (ev.target !== this) return; console.clear(); console.log(this._node.id); }; <div id="tree"></div>

我有类似的问题,几天前必须从平面数组显示文件夹树。我在TypeScript中没有看到任何解决方案,所以我希望它会有帮助。

在我的情况下,主父只有一个,rawData数组也不需要排序。解决方案基于准备临时对象 {parentId: [child1, child2,…]]}

示例原始数据

const flatData: any[] = Folder.ofCollection([
  {id: '1', title: 'some title' },
  {id: '2', title: 'some title', parentId: 1 },
  {id: '3', title: 'some title', parentId: 7 },
  {id: '4', title: 'some title', parentId: 1 },
  {id: '5', title: 'some title', parentId: 2 },
  {id: '6', title: 'some title', parentId: 5 },
  {id: '7', title: 'some title', parentId: 5 },

]);

文件夹的定义

export default class Folder {
    public static of(data: any): Folder {
        return new Folder(data);
    }

    public static ofCollection(objects: any[] = []): Folder[] {
        return objects.map((obj) => new Folder(obj));
    }

    public id: string;
    public parentId: string | null;
    public title: string;
    public children: Folder[];

    constructor(data: any = {}) {
        this.id = data.id;
        this.parentId = data.parentId || null;
        this.title = data.title;
        this.children = data.children || [];
    }
}

解决方案:返回扁平参数的树结构的函数

    public getTree(flatData: any[]): Folder[] {
        const addChildren = (item: Folder) => {
            item.children = tempChild[item.id] || [];
            if (item.children.length) {
                item.children.forEach((child: Folder) => {
                    addChildren(child);
                });
            }
        };

        const tempChild: any = {};
        flatData.forEach((item: Folder) => {
            const parentId = item.parentId || 0;
            Array.isArray(tempChild[parentId]) ? tempChild[parentId].push(item) : (tempChild[parentId] = [item]);
        });

        const tree: Folder[] = tempChild[0];
        tree.forEach((base: Folder) => {
            addChildren(base);
        });
        return tree;
    }

这是一个旧线程,但我认为更新永远不会伤害,与ES6你可以做到:

const data = [{ id: 1, parent_id: 0 }, { id: 2, parent_id: 1 }, { id: 3, parent_id: 1 }, { id: 4, parent_id: 2 }, { id: 5, parent_id: 4 }, { id: 8, parent_id: 7 }, { id: 9, parent_id: 8 }, { id: 10, parent_id: 9 }]; const arrayToTree = (items=[], id = null, link = 'parent_id') => items.filter(item => id==null ? !items.some(ele=>ele.id===item[link]) : item[link] === id ).map(item => ({ ...item, children: arrayToTree(items, item.id) })) const temp1=arrayToTree(data) console.log(temp1) const treeToArray = (items=[], key = 'children') => items.reduce((acc, curr) => [...acc, ...treeToArray(curr[key])].map(({ [`${key}`]: child, ...ele }) => ele), items); const temp2=treeToArray(temp1) console.log(temp2)

希望它能帮助到别人

我的解决方案:

允许双向映射(根到叶,叶到根) 返回所有节点、根节点和叶节点 一次数据传递和非常快的性能 香草Javascript

/**
 * 
 * @param data items array
 * @param idKey item's id key (e.g., item.id)
 * @param parentIdKey item's key that points to parent (e.g., item.parentId)
 * @param noParentValue item's parent value when root (e.g., item.parentId === noParentValue => item is root)
 * @param bidirectional should parent reference be added
 */
function flatToTree(data, idKey, parentIdKey, noParentValue = null, bidirectional = true) {
  const nodes = {}, roots = {}, leaves = {};

  // iterate over all data items
  for (const i of data) {

    // add item as a node and possibly as a leaf
    if (nodes[i[idKey]]) { // already seen this item when child was found first
      // add all of the item's data and found children
      nodes[i[idKey]] = Object.assign(nodes[i[idKey]], i);
    } else { // never seen this item
      // add to the nodes map
      nodes[i[idKey]] = Object.assign({ $children: []}, i);
      // assume it's a leaf for now
      leaves[i[idKey]] = nodes[i[idKey]];
    }

    // put the item as a child in parent item and possibly as a root
    if (i[parentIdKey] !== noParentValue) { // item has a parent
      if (nodes[i[parentIdKey]]) { // parent already exist as a node
        // add as a child
        (nodes[i[parentIdKey]].$children || []).push( nodes[i[idKey]] );
      } else { // parent wasn't seen yet
        // add a "dummy" parent to the nodes map and put the item as its child
        nodes[i[parentIdKey]] = { $children: [ nodes[i[idKey]] ] };
      }
      if (bidirectional) {
        // link to the parent
        nodes[i[idKey]].$parent = nodes[i[parentIdKey]];
      }
      // item is definitely not a leaf
      delete leaves[i[parentIdKey]];
    } else { // this is a root item
      roots[i[idKey]] = nodes[i[idKey]];
    }
  }
  return {roots, nodes, leaves};
}

使用的例子:

const data = [{id: 2, parentId: 0}, {id: 1, parentId: 2} /*, ... */];
const { nodes, roots, leaves } = flatToTree(data, 'id', 'parentId', 0);