使用lodashjs api通过父ID合并数组

时间:2017-11-14 09:45:18

标签: arrays lodash

我有一个结构如下所示的数组:

[
  {
    "id": 1,
    "type": "SUB",
    "username": "jksub04m1s8"
  },
  {
    "id": 2,
    "parent_id": 1,
    "type": "SUB",
    "username": "jksub04m2s4"
  },
  {
    "id": 3,
    "parent_id": 1,
    "type": "OPERATOR",
    "username": "mountbetoperator"
  },
  {
    "id": 4,
    "parent_id": 2,
    "type": "SUB",
    "username": "jksub04m2s2"
  },
  {
    "id": 5,
    "type": "SUB",
    "username": "jksub04m1s8"
  },
  {
    "id": 6,
    "type": "SUB",
    "parent_id": 2,
    "username": "jksub04m1s8"
  }
]

我通过映射父ID来编写一个重组它的函数,如下所示:

[
  {
    "id": 1,
    "type": "SUB",
    "username": "jksub04m1s8",
    "children": [
      {
        "id": 2,
        "parent_id": 1,
        "type": "SUB",
        "username": "jksub04m2s4",
        "children": [
          {
            "id": 4,
            "parent_id": 2,
            "type": "SUB",
            "username": "jksub04m2s2"
          },
          {
            "id": 6,
            "type": "SUB",
            "parent_id": 2,
            "username": "jksub04m1s8"
          }
        ]
      }...
]

但我的功能太长了,让这个过程变得如此缓慢,实际上我有大约10000多条这样的记录。

我可以使用lodash api进行重组吗?

1 个答案:

答案 0 :(得分:0)

你可以简单地使用一个JS函数,使用map并迭代数组两次就可以实现这一点,你甚至不需要递归函数或复杂的代码。这是我写的一个你可以尝试的例子。



var arr = arr = [{
        "id": 1,
        "type": "SUB",
        "username": "jksub04m1s8"
    },
    {
        "id": 2,
        "parent_id": 1,
        "type": "SUB",
        "username": "jksub04m2s4"
    },
    {
        "id": 3,
        "parent_id": 1,
        "type": "OPERATOR",
        "username": "mountbetoperator"
    },
    {
        "id": 4,
        "parent_id": 2,
        "type": "SUB",
        "username": "jksub04m2s2"
    },
    {
        "id": 5,
        "type": "SUB",
        "username": "jksub04m1s8"
    },
    {
        "id": 6,
        "type": "SUB",
        "parent_id": 2,
        "username": "jksub04m1s8"
    }
];

function transform(input) {
    var res = [],
        idx,
        map = {},
        addedToParentMap = {},
        temp,
        tempParent,
        curr,
        twiceLen = input.length * 2;
    for (idx = 0; idx < twiceLen; idx++) {
        curr = input[idx % input.length];
        temp = map[curr.id] || Object.assign({
            children: []
        }, curr);

        if (!temp.parent_id && !map[curr.id]) {
            res.push(temp);
        } else {
            tempParent = map[temp.parent_id];
            if (tempParent && !addedToParentMap[temp.id]) {
                tempParent.children.push(temp);
                addedToParentMap[temp.id] = true;
            }
        }
        map[curr.id] = temp;
    }
    return res;
}

var res = transform(arr);
console.log(res);
&#13;
&#13;
&#13;