美文网首页
根据id pid 转树

根据id pid 转树

作者: ShoneSingLone | 来源:发表于2020-09-18 11:36 被阅读0次
let _ = require("lodash");
var data = [{ "id": 1, "key": "key1", "value":"value1", "pid": 0 }, { "id": 2, "key": "key2", "value":"value2", "pid": 1 }, { "id": 3, "key": "key3", "value":"value3", "pid": 1 }, { "id": 4, "key": "key4", "value":"value4", "pid": 3 }, { "id": 5, "key": "key5", "value":"value5", "pid": 4 }, { "id": 6, "key": "key6", "value":"value6", "pid": 4 }];
var root;
var dataObj = _.reduce(data, function (target, i) {
    if (String(i.pid) === "0") {
        root = i;
    } else {
        target[i.id] = i;
    }
    return target;
}, {});

function buildTree(dataObj, root) {
    /* findChildren */
    var children = [];
    _.forEach(dataObj, function (i) {
        console.log("forEach -> i", i);
        if (!i) return;
        var isChild = i.pid === root.id;
        if (isChild) {
          delete dataObj[i.id];
          console.log(_.map(dataObj, i => i.id));
          children.push(buildTree(dataObj, i));
        }
    });
    if (children.length > 0) {
        root.children = children;
    }
    return root;
}
var tree = buildTree(dataObj, root);
console.table(JSON.stringify(tree, null, 2));
//Result
{
  "id": 1,
  "key": "key1",
  "value": "value1",
  "pid": 0,
  "children": [
    {
      "id": 2,
      "key": "key2",
      "value": "value2",
      "pid": 1
    },
    {
      "id": 3,
      "key": "key3",
      "value": "value3",
      "pid": 1,
      "children": [
        {
          "id": 4,
          "key": "key4",
          "value": "value4",
          "pid": 3,
          "children": [
            {
              "id": 5,
              "key": "key5",
              "value": "value5",
              "pid": 4
            },
            {
              "id": 6,
              "key": "key6",
              "value": "value6",
              "pid": 4
            }
          ]
        }
      ]
    }
  ]
}

相关文章

网友评论

      本文标题:根据id pid 转树

      本文链接:https://www.haomeiwen.com/subject/pxtjyktx.html