当有新密钥时合并两个对象

时间:2016-01-24 22:55:55

标签: javascript jquery object merge

我有两个具有以下结构的对象,并尝试将它们合并在一起。

我用$ .merge尝试了它,但它不是预期的结果。

对象1 - 并非所有属性

{
    "id": 23,
    "name": "Article",
    "related": 15 "items": [{
        "name": "Test1",
        "items": [{
            "name": "Test2",
            "items": [{
                "name": "Test3",
                "items": [{
                    "name": "Test4",
                    "items": [{
                        "name": "Test5",
                        "items": [{
                            "name": "Test6",
                        }]
                    }]
                }]
            }]
        }]
    }]
}, {
    "id": 24…
}

对象2 - 具有其他属性

{
    "id": 23,
    "name": "Article",
    "related": 15 "items": [{
        "name": "Test1",
        "id": 34 "items": [{
            "name": "Test2",
            "id": 57 "items": [{
                "name": "Test3",
                "id": 92 "items": [{
                    "name": "THIS ONE IS NOT EXISTING IN OBJECT 1 AND SHOULD NOT GET MERGED",
                    "id": 789
                }, {
                    "name": "Test4",
                    "id": 12 "items": [{
                        "name": "Test5",
                        "id": 321 "items": [{
                            "name": "Test6",
                            "id": 285
                        }]
                    }]
                }]
            }]
        }]
    }]
}, {
    "id": 24…
}

有谁知道一些聪明的伎俩? jQuery甚至是必要的吗?

2 个答案:

答案 0 :(得分:2)

jQuery的$ .extend会做你想做的事。

//merging two objects into new object
var new_object = $.extend(true, {}, object1, object2);

//merge object2 into object1
$.extend(true, object1, object2);

第一个参数:deep:true,请参阅:https://api.jquery.com/jquery.extend/

答案 1 :(得分:1)

没有jquery:https://jsfiddle.net/sLhcbewh/

function mymerge_sub(object1, object2)
{
  for(var i in object2) {
    if(i == 'items')
      continue;

    console.log(i);
    if(object1[i] === undefined) {
      console.log(i + ' not found');
      object1[i] = object2[i];
    }
  }

  if(object1.items !== undefined) {
    mymerge_sub(object1.items[0], object2.items[0])
  }
}

function mymerge(object1, object2) {
  var ret = JSON.parse(JSON.stringify(object1));
  mymerge_sub(ret, object2); // save obj 1
  return ret;
}

var obj3 = mymerge(obj1, obj2);

如果你想要几个项目,你必须循环mymerge_sub(object1.items [j] ...)。