如何合并维数组

how to merge dimensional arrays

var list1 = [
    {
        id: 'node1',
        children: [
            {
                id: 'node11',
                children: []
            }
        ]
    }
];

var list2 = [
    {
        id: 'node1',
        children: [
            {
                id: 'node13',
                children: []
            }
        ]
    }
];
var resultList = [
    {
        id: 'node1',
        children: [
            {
                id: 'node11',
                children: []
            }, {
                id: 'node13',
                children: []
            }
        ]
    }
];

我所有的数组都是树,一个节点只能属于一个父节点。 我想合并 list1 和 list2 并得到 resultList.I 尝试了很多方法,递归回调,字符串搜索和替换等等,但我还是想不通。

下面的代码将合并两个树数组的所有级别,而不仅仅是最上面的级别:

var list1 = ...
var list2 = ...

var addNode = function(nodeId, array) {
  array.push({id: nodeId, children: []});
};

var placeNodeInTree = function(nodeId, parent, treeList) {
  return treeList.some(function(currentNode){

    // If currentNode has the same id as the node we want to insert, good! Required for root nodes.
    if(currentNode.id === nodeId) {
      return true;  
    }

    // Is currentNode the parent of the node we want to insert?
    if(currentNode.id === parent) {

      // If the element does not exist as child of currentNode, create it
      if(!currentNode.children.some(function(currentChild) {
        return currentChild.id === nodeId;
      })) addNode(nodeId, currentNode.children);

      return true;
    } else {

      // Continue looking further down the tree
      return placeNodeInTree(nodeId, parent, currentNode.children);
    }
  });
};

var mergeInto = function(tree, mergeTarget, parentId) {
  parentId = parentId || undefined;
  tree.forEach(function(node) {

    // If parent has not been found, placeNodeInTree() returns false --> insert as root element
    if(!placeNodeInTree(node.id, parentId, mergeTarget)){
      list1.push({id: node.id, children:[]});
    }

    mergeInto(node.children, mergeTarget, node.id);

  });
};

mergeInto(list2, list1);

document.write('<pre>');
document.write(JSON.stringify(list1, null, 4));
document.write('</pre>');

查看 JSBin 上的实时代码:http://jsbin.com/wikaricita/3/edit?js,output

请注意,此算法的复杂度为 O(n^2),这意味着它无法很好地扩展。如果树变得非常大或性能是一个关键问题,您可能想要研究解决此问题的其他方法。

如果我没理解错的话,你希望它通过 id 压缩。

function getCompactById(arr) { // must have the same id
    var res = [];
    var obj = {};
    obj.id = arr[0][0].id;
    obj.children = [];
    for(var i = 0; i < arr.length; i += 1) {
        obj.children.push(arr[i][0].children[0]);
    }
    res.push(obj);
    return res;
}

数组看起来像 var arr = [list1, list2]; 在函数中 create 一个 array 和一个 object。该对象获得一个 id 和一个数组。 id 始终相同,因此我们从第一个数组中获取它。遍历数组并推送所有对象 arr[i][0].children[0]。循环后将 obj 推入数组。 Return 结果数组。

Demo