Convert an one-dimensional array with a parent-child relationship into tree-structured (multidimensional) data

known original data:

var data=[
  { id: 40, parentId: 31, note: "" }, 

  { id: 20, parentId: 11, note: "" },
  { id: 22, parentId: 20, note: "dsadas" },
  { id: 12, parentId: null, note: "dsadasads" }, 
  { id: 11, parentId: undefined, note: "dqwds" }, 
  { id: 24, parentId: 22, note: "" },
  { id: 34, parentId: 22, note: "" }
]

questions to consider:

  • do not change the source data
  • avoid circular references, that is, the parentId of an is b and the parentId of b is a
< hr >

use your brain and give an optimal solution


Let's start with a function comment:

/**
 * ()
 * console.log(JSON.stringify(setTreeData(data), null, 2));
 * ============================================
 * @param {*Array} data 
 */

Let's go to the specific code:

function fnSetTreeData(data) {
  var data = [...data];
  var tree = data.filter((father) => {
    var branchArr = data.filter((child) => {
      if (father.id == child.parentId) child._hasParent = true;
      return father.id == child.parentId;

      // MARK  ? 
      // if (father.id == child.parentId) child._hasParent = true;
      // return child._hasParent
    });
    if (branchArr.length > 0) father.children = branchArr;
    return !father._hasParent;
  });

  // MARK 
  tree = tree.filter((item) => {
    return !item._hasParent;
  })
  return tree
}

console.log(JSON.stringify(fnSetTreeData(data), null, 2));

as for how to solve the problem of circular reference , first sort the array with sort , and then count PP in filter each time

?

you have to give a test data:
var data = [
  { id: 40, parentId: 31, note: "" }, 

  { id: 20, parentId: 11, note: "" },
  { id: 22, parentId: 20, note: "dsadas" },
  { id: 12, parentId: null, note: "dsadasads" }, 
  { id: 11, parentId: undefined, note: "dqwds" }, 
  { id: 24, parentId: 22, note: "" },
  { id: 34, parentId: 22, note: "" }
];


<br><br><strong>idparentIditemitemchilders</strong><br><strong>parentId</strong>

  function setTreeData(arg) {
    var data = [...arg];
    var sort = [];
    var parentIdArr = []
    data.map((item, idx) => {
      item.childers = [];
      let pp = Object.assign({}, data)
      data.map((subitem, subidx) => {
        parentIdArr.push(subitem.id)
        if (item.id === subitem.parentId) {
          item.childers.push(subitem);
        }
      })
      var obj = Object.assign({}, item);
      parentIdArr = [...new Set(parentIdArr)]
      if (item.parentId - 1 > 0) {
        parentIdArr.indexOf(item.parentId) == -1 ? sort.push(item) : ""
      } else {
        sort.push(item)
      }
    })
    return sort
  }
Menu