首页 > 解决方案 > 在 JavaScript 中合并两个多维数组的口袋

问题描述

我有两个具有下面给出的结构的数组。

我需要将两个数组的值合二为一,并且顺序应该是按顺序排列的。我也需要保留其他口袋。

标题应该首先是孩子,然后是下一个标题,然后是下一个孩子的口袋。

const header = {
    "list": [{
      "name": "header-a",
      "id": "id-a"
    }, {
      "name": "header-b",
      "id": "id-b"
    }]
  };
  const child = {
    "list": [{
      "name": "child",
      "id": "c1",
      'type': "id-a"
    },
      {
        "name": "child 2",
        "id": "c2",
        'type': "id-a"
      },
      {
        "name": "child 4",
        "id": "c4",
        'type': "id-b"
      },
      {
        "name": "child-5",
        "id": "c5",
        'type': "id-b"
      }]
  };

预期的结果是

  const result = {
    "list": [{
      "name": "header-a",
      "header": true,
    },
      {
        "name": "child",
        "id": "c1",
        'type': "id-a"
      },
      {
        "name": "child 2",
        "id": "c2",
        'type': "id-a"
      },
      {
        "name": "header-b",
        "header": true,
      },
      {
        "name": "child 4",
        "id": "c4",
        'type': "id-b"
      },
      {
        "name": "child-5",
        "id": "c5",
        'type': "id-b"
      }]
  };

标签: javascriptarraysmultidimensional-array

解决方案


您遍历标题,对于每个标题,您将类似的项目推入“组合”数组{ name: header.name, header: true },然后过滤所有type等于标题的子项id并将它们也推入数组:

const header = {
  "list": [{
    "name": "header-a",
    "id": "id-a"
  }, {
    "name": "header-b",
    "id": "id-b"
  }]
};

const child = {
  "list": [{
      "name": "child",
      "id": "c1",
      'type': "id-a"
    },
    {
      "name": "child 2",
      "id": "c2",
      'type': "id-a"
    },
    {
      "name": "child 4",
      "id": "c4",
      'type': "id-b"
    },
    {
      "name": "child-5",
      "id": "c5",
      'type': "id-b"
    }
  ]
};

const combined = { list: [] };
header.list.forEach(h => {
  combined.list.push({ name: h.name, header: true });
  child.list.filter(c => c.type === h.id).forEach(c => combined.list.push(c));
});

console.log(combined);


推荐阅读