2016-09-21 52 views
1

我有2個獨立的數組,我需要合併到第三個數組中,以便我可以獲取所需的所有數據。 基本上,第一個數組有一個ID和名稱,爲了獲得我需要在第二個數組內搜索的地址並匹配ID,所以我可以獲取該人的所有數據。Javascript將2個數組合併到第3個數組中以獲取所需的所有數據

下面是數據和代碼:

//Array 1 
var myPeopleArray = [{"people":[{"id":"123","name":"name 1"},{"id":"456","name":"name 2"}]}]; 

//Array 2 
var myPersonArray = [{"person":[{"id":"123","address":"address 1"},{"id":"456","address":"address 2"}]}]; 

    var arrayLength = myPeopleArray[0].people.length; 

    for (var i = 0; i < arrayLength; i++) { 

     console.log("id: " + myPeopleArray[0].people[i].id); 

    } 

//Wanted Result: 

[{"people":[ 

    { 
     "id":"123", 
     "name":"name 1", 
     "address":"address 1" 
    }, 

    { 
     "id":"456", 
     "name":"name 2", 
     "address":"address 2" 
    } 
] 

}] 

我怎樣才能做到這一點?

+0

你做任何谷歌搜索? http://stackoverflow.com/questions/13514121/merging-two-collections-using-underscore-js。如果你不能使用下劃線,那麼也會有幫助你的結果。 – Nix

+0

你爲什麼 - 或者你的腳本爲什麼 - 首先創建兩個數組? –

回答

0

您可以迭代這兩個數組並使用連接的屬性構建新對象。

var myPeopleArray = [{ "people": [{ "id": "123", "name": "name 1" }, { "id": "456", "name": "name 2" }] }], 
 
    myPersonArray = [{ "person": [{ "id": "123", "address": "address 1" }, { "id": "456", "address": "address 2" }] }], 
 
    hash = Object.create(null), 
 
    joined = [], 
 
    joinById = function (o) { 
 
     if (!(o.id in hash)) { 
 
      hash[o.id] = {}; 
 
      joined.push(hash[o.id]); 
 
     } 
 
     Object.keys(o).forEach(function (k) { 
 
      hash[o.id][k] = o[k]; 
 
     }); 
 
    }; 
 

 
myPeopleArray[0].people.forEach(joinById); 
 
myPersonArray[0].person.forEach(joinById); 
 

 
console.log(joined);

+0

如果myPersonArray上的id字段具有不同的名稱,該怎麼辦? –

+0

在這種情況下你想要什麼?只是覆蓋,如上所述或保留舊名稱? –

+0

基本上,目前你正在與ID匹配id我需要做一個人數組上的字段名稱是ID和Person數組上的匹配字段是另一個名字...我需要在代碼中更改什麼這個? –

1
var myPeopleArray = [{"people":[{"id":"123","name":"name 1"}, {"id":"456","name":"name 2"}]}]; 
var myPersonArray = [{"person":[{"id":"123","address":"address 1"}, {"id":"456","address":"address 2"}]}]; 

for(var i=0;i<myPeopleArray[0].people.length;i++) 
{ 
myPeopleArray[0].people[i].address = myPersonArray[0].person[i].address; 
} 
document.write(JSON.stringify(myPeopleArray)); 
相關問題