简体   繁体   中英

Merge two objects when there's a new key

I have two objects with the following structure and tried to merge them together.

I tried it with $.merge but its not the expected result.

Object 1 - Has not all attributes

{
    "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…
}

Object 2 - with additional attributes

{
    "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…
}

Does anyone know some smart trick? Is jQuery even necessary?

jQuery's $.extend will do what you want.

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

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

The 1st parameter: deep:true, see: https://api.jquery.com/jquery.extend/

Without 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);

If you want several items, you have to loop mymerge_sub(object1.items[j]... ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM