javascriptjquerytreeviewhierarchical

Hierarchical tree view


I want to create a hierarchical from my MySql data response, it has jsut id and sponsor_id. I am not sure how to start, please help me solving this

[ { "id": 2723021, "sponsor_id": "2723020" }, { "id": 2723022, "sponsor_id": "2723021" }, { "id": 2723023, "sponsor_id": "2723021" }, { "id": 2723024, "sponsor_id": "2723021" }, { "id": 2723025, "sponsor_id": "2723022" }, { "id": 2723026, "sponsor_id": "2723022" }, { "id": 2723027, "sponsor_id": "2723022" }, { "id": 2723028, "sponsor_id": "2723023" }, { "id": 2723029, "sponsor_id": "2723023" }, { "id": 2723030, "sponsor_id": "2723023" }, { "id": 2723031, "sponsor_id": "2723024" }, { "id": 2723032, "sponsor_id": "2723024" }, { "id": 2723033, "sponsor_id": "2723024" }, { "id": 2723034, "sponsor_id": "2723025" } ]

I want to make it like this

Nothing coming in my mind what & how to start


Solution

  • Just create a map by item id, and find parents and add children to them, if no parent is found it's the root item.

    const arr = [ { "id": 2723021, "sponsor_id": "2723020" }, { "id": 2723022, "sponsor_id": "2723021" }, { "id": 2723023, "sponsor_id": "2723021" }, { "id": 2723024, "sponsor_id": "2723021" }, { "id": 2723025, "sponsor_id": "2723022" }, { "id": 2723026, "sponsor_id": "2723022" }, { "id": 2723027, "sponsor_id": "2723022" }, { "id": 2723028, "sponsor_id": "2723023" }, { "id": 2723029, "sponsor_id": "2723023" }, { "id": 2723030, "sponsor_id": "2723023" }, { "id": 2723031, "sponsor_id": "2723024" }, { "id": 2723032, "sponsor_id": "2723024" }, { "id": 2723033, "sponsor_id": "2723024" }, { "id": 2723034, "sponsor_id": "2723025" } ]
    
    
    const map = arr.reduce((r, item) => (r[item.id] = item, r), {});
    let root;
    Object.values(map).forEach(item => {
      const parent = map[item.sponsor_id];
      parent ? (parent.children ??= []).push(item) : root = item;
    });
    
    console.log(root);

    A simpler version:

    const arr = [ { "id": 2723021, "sponsor_id": "2723020" }, { "id": 2723022, "sponsor_id": "2723021" }, { "id": 2723023, "sponsor_id": "2723021" }, { "id": 2723024, "sponsor_id": "2723021" }, { "id": 2723025, "sponsor_id": "2723022" }, { "id": 2723026, "sponsor_id": "2723022" }, { "id": 2723027, "sponsor_id": "2723022" }, { "id": 2723028, "sponsor_id": "2723023" }, { "id": 2723029, "sponsor_id": "2723023" }, { "id": 2723030, "sponsor_id": "2723023" }, { "id": 2723031, "sponsor_id": "2723024" }, { "id": 2723032, "sponsor_id": "2723024" }, { "id": 2723033, "sponsor_id": "2723024" }, { "id": 2723034, "sponsor_id": "2723025" } ]
    
    
    const map = {};
    for(const item of arr) map[item.id] = item;
    let root;
    for(const id in map){
      const item = map[id];
      const parent = map[item.sponsor_id];
      if(parent){
        if(!parent.children) parent.children = [];
        parent.children.push(item);
      }else{
        root = item;
      }
    }
    
    console.log(root);