2017-04-09 47 views
0

我有兩個多維數組並希望將其合併到僅包含常見匹配標記的單個數據源中。Javascript合併兩個具有常見匹配元素的多維數組

//的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 

回答

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

+0

你好@Nina肖爾茨還有一個問題,你也許可以幫助解決 - http://stackoverflow.com/questions/43415966/d3-js-chemical-tube-bar-chart/43461927 #43461927 –

相關問題