如何通过2个对象的相同值创建对象?

时间:2017-12-26 12:41:55

标签: javascript

我试图通过比较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"}}}]

更明确:

  1. 在两个匹配id' s
  2. 的对象中查找
  3. 将它们堆叠在一个对象中...所以新对象将包含来自它们的匹配id对象....
  4. 我试过了:

    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个结果

    Fiddle

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; }