我有以下两个对象:
var object1 = {
"user1@yahoo.com": [
{
"status": "Unread",
"message": "Some message 1",
"senderId": "0063f297-0da6-4c23-9a53-0480c273d177",
"id": "088b71bc-5b64-4f09-bba4-cf88b3cc598e",
"time": "2016-05-13T10:30:11.495Z"
},
{
"status": "Unread",
"message": "Some other message 2",
"senderId": "0063f297-0da6-4c23-9a53-0480c273d177",
"id": "39b2850b-d8ac-4d23-9fa6-e7056fb6c030",
"time": "2016-05-13T10:30:03.310Z"
}
]
};
var object2 = {
"user1@yahoo.com": [
{
"message": "Some message 1",
"id": "088b71bc-5b64-4f09-bba4-cf88b3cc598e",
"time": "2016-05-13T10:30:11.495Z"
},
{
"message": "Some other message 2",
"id": "39b2850b-d8ac-4d23-9fa6-e7056fb6c030",
"time": "2016-05-13T10:30:03.310Z"
}
],
"user3@yahoo.com": [
{
"message": "Some message 1",
"id": "088b71bc-5b64-4f09-bba4-cf88b3cc598e",
"time": "2016-05-13T10:30:11.495Z"
},
{
"message": "Some other message 1",
"id": "39b2850b-d8ac-4d23-9fa6-e7056fb6c030",
"time": "2016-05-13T10:30:03.310Z"
}
]
};
我需要将它们组合成一个看起来像这样的对象:
var object3 = {
"user1@yahoo.com": [
{
"status": "Unread",
"message": "Some message 1",
"senderId": "0063f297-0da6-4c23-9a53-0480c273d177",
"id": "088b71bc-5b64-4f09-bba4-cf88b3cc598e",
"time": "2016-05-13T10:30:11.495Z"
},
{
"status": "Unread",
"message": "Some other message 2",
"senderId": "0063f297-0da6-4c23-9a53-0480c273d177",
"id": "39b2850b-d8ac-4d23-9fa6-e7056fb6c030",
"time": "2016-05-13T10:30:03.310Z"
},
{
"message": "Some message 1",
"id": "088b71bc-5b64-4f09-bba4-cf88b3cc598e",
"time": "2016-05-13T10:30:11.495Z"
},
{
"message": "Some other message 2",
"id": "39b2850b-d8ac-4d23-9fa6-e7056fb6c030",
"time": "2016-05-13T10:30:03.310Z"
}
]
}
标识邮件组的电子邮件是相同的。
答案 0 :(得分:3)
首先,从每个对象获取密钥。然后,对于两个对象中存在的每封电子邮件,连接其列表。
var keys1List = Object.getOwnPropertyNames(array1),
keys2List = Object.getOwnPropertyNames(array2),
result = {};
keys1List.forEach(function(email) {
if (keys2List.indexOf(email) > -1) {
result[email] = array1[email].concat(array2[email]);
}
});
请注意,您的array1
,array2
和array3
变量实际上是对象而不是数组。我建议你改变他们的名字,以便他们不会混淆其他人(甚至你,后来)会阅读这段代码。
答案 1 :(得分:2)
var map = Object.keys(array1).reduce(function( map, email ) {
map[email] = array1[email];
if (array2.hasOwnProperty(email)) map[email] = map[email].concat(array2[email]);
return map;
}, {});
答案 2 :(得分:0)
这种组合就像你想要的那样:
Object.combineArrays = function(obj1, obj2) {
var sizeA = 0, key, keyB;
for (key in obj2) {
if (obj1.hasOwnProperty(key) && obj2.hasOwnProperty(key)) {
for (keyB in obj2[key]) {
obj1['user1@yahoo.com'].push( obj2[key][keyB] );
}
sizeA++;
}
}
return obj1;
};
var newObjects = Object.combineArrays(obj1, obj2);
console.log(newObjects);
答案 3 :(得分:-1)
使用下划线
_.mapObject(array1,function(val,key){
return _.union(val,array2[key]);
})