Javascript合并两个具有公共匹配元素的多维数组

时间:2017-04-09 12:45:55

标签: javascript arrays multidimensional-array merge

我有两个多维数组,并希望将其合并为一个只包含常用匹配标记的数据源。

//的jsfiddle http://jsfiddle.net/Qh9X5/10173/

// array 1

    var array1 = [{
            "Skills & Expertise": [{
              "id": 2,
              "tag": "Javascript"
            }, {
              "id": 3,
              "tag": "Design"
            }],
            "Location": [{
              "id": 0,
              "tag": "London"
            }, {
              "id": 1,
              "tag": "Germany"
            }],
            "Company": [{
              "id": 0,
              "tag": "Cheesestrings"
            }]
}];

// array 2

var array2 = [{
            "Skills & Expertise": [{
              "id": 0,
              "tag": "JAVA"
            }, {
              "id": 1,
              "tag": "PHP"
            }, {
              "id": 2,
              "tag": "Javascript"
            }],
            "Location": [{
              "id": 0,
              "tag": "London"
            }],
            "Company": [{
              "id": 0,
              "tag": "Cheesestrings"
            }, {
              "id": 1,
              "tag": "Bakerlight"
            }]
          }]

所以结果应该是这样的

//期望的结果

  var array3 = [{
                "Skills & Expertise": [{
                  "id": 2,
                  "tag": "Javascript"
                }],
                "Location": [{
                  "id": 0,
                  "tag": "London"
                }],
                "Company": [{
                  "id": 0,
                  "tag": "Cheesestrings"
                }]
    }];

我是首先使用联系人合并两个数组 - 然后删除两者中不存在的元素?

var array3 = array1.concat(array2); // Merges both arrays

1 个答案:

答案 0 :(得分:1)

您可以使用反映数组项的哈希表,并使用嵌套方法获取哈希值和结果集。

var array1 = [{ "Skills & Expertise": [{ id: 2, tag: "Javascript" }, { id: 3, tag: "Design" }], Location: [{ id: 0, tag: "London" }, { id: 1, tag: "Germany" }], Company: [{ id: 0, tag: "Cheesestrings" }] }],
    array2 = [{ "Skills & Expertise": [{ id: 0, tag: "JAVA" }, { id: 1, tag: "PHP" }, { id: 2, tag: "Javascript" }], Location: [{ id: 0, tag: "London" }], Company: [{ id: 0, tag: "Cheesestrings" }, { id: 1, tag: "Bakerlight" }] }],
    hash = [],
    result;

array1.forEach(function (o, i) {
    Object.keys(o).forEach(function (k) {
        o[k].forEach(function (a) {
            hash[i] = hash[i] || {};
            hash[i][[k, a.tag].join('|')] = true;
        });
    });
});

result = array2.map(function (o, i) {
    var temp = {};
    Object.keys(o).forEach(function (k) {
        o[k].forEach(function (a) {
            if ((hash[i] || {})[[k, a.tag].join('|')]) {
                temp[k] = temp[k] || [];
                temp[k].push(a);
            }
        });
    });
    return temp;
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }