簡體   English   中英

Javascript將具有共同匹配元素的兩個多維數組合並

[英]Javascript merging two multidimensional arrays with common matching elements

我有兩個多維數組,想將其合並到僅包含通用匹配標簽的單個數據源中。

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

//數組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"
            }]
}];

//數組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

您可以使用反映數組項的哈希表,並使用嵌套的方法獲取哈希和結果集。

 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; } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM