Javascript将2个数组合并到第3个数组中以获取所需的所有数据

时间:2016-09-21 10:48:05

标签: javascript arrays

我有两个独立的阵列,我需要合并到第三个阵列,这样我就可以获得所需的所有数据。 基本上第一个数组有一个id和名称,为了获得我需要在第二个数组内搜索并匹配id的地址,所以我可以获得该人的所有数据。

以下是数据和代码:

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

}]

我该怎么做?

2 个答案:

答案 0 :(得分: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));

答案 1 :(得分:0)

您可以迭代两个数组并使用连接的属性构建新对象。

&#13;
&#13;
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);
&#13;
&#13;
&#13;