2016-09-21 104 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)); 
相关问题