我试图通过比较2个对象来创建一个对象,如果有相同的id,那么创建一个对象。
例如:
obj1 = [{"id":1,"name":"john"},{"id":2,"name":"kile"},{"id":3,"name":"kenny"},
{"id":4,"name":"stan"}]
obj2 = [{"id":1,"name":"dan"},{"id":1,"name":"ben"},{"id":1,"name":"sarah"},
{"id":2,"name":"kelly"}]
我正在寻找的结果是:
result = [{1:{"id":1,"name":"john"},{"id":1,"name":"dan"},
{"id":1,"name":"ben"},{"id":1,"name":"sarah"},
//both objects from obj1 & obj 2 which holds the same ID are now in new
object "1" - which is the id that's common to them//
{2:{{"id":2,"name":"kile"},
{"id":2,"name":"kelly"}}}]
更明确:
我试过了:
var obj_names_1 = [{"id":1,"name":"john"},{"id":2,"name":"kile"},
{"id":3,"name":"kenny"},
{"id":4,"name":"stan"}];
var obj_names_2 = [{"id":1,"name":"dan"},{"id":1,"name":"ben"},
{"id":1,"name":"sarah"},
{"id":2,"name":"kelly"}];
function getMessages(obj1, obj2){
var messages_tab = [];
$.each(obj1, function(){
var messages_wrap = this;
var recieved_messages_id = this.id;
$.each(obj2, function(){
var sent_messages_id = this.id;
if(recieved_messages_id == sent_messages_id){
messages_tab.push({1:[this,messages_wrap]}); // key 0 should
be the common id
}
});
});
return messages_tab;
}
console.log(getMessages(obj_names_1,obj_names_2));
但这里的第一个问题是它没有超过1个结果
答案 0 :(得分:2)
您可以array#concat
两个阵列,然后使用array#reduce
推送具有相同id
的数组中的对象。
注意:与id
对应的值应为数组。
var obj1 = [{"id":1,"name":"john"},{"id":2,"name":"kile"},{"id":3,"name":"kenny"},{"id":4,"name":"stan"}],
obj2 = [{"id":1,"name":"dan"},{"id":1,"name":"ben"},{"id":1,"name":"sarah"},{"id":2,"name":"kelly"}]
result = obj1.concat(obj2).reduce((r,o) => {
r[o.id] = r[o.id] || [];
r[o.id].push(o);
return r;
},{});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }