Good day.
There are two some unknown objects. They need to be combined into one. What should be connected according to the rules:

  • if in the object a and in the object b there is the same object (or a subobject of ANY nesting), then leave the object from b ;
  • if in object a and in object b there is the same object and it is an array , then both of these arrays must be joined;
  • if in object b there is an object missing in a , then add it.
  • You must either change a , or get a new object.

I will give an example:

 a: { car: "WW", detail:{ wheel: { left: "good", right:"bad" } }, props: [ {prop1: "1"}, {prop1: "2"}, {prop1: "3"} ] }; // Теперь объект b, который надо совместить: b: { detail:{ wheel: { left: "bad",//изменяем свойство из a на это center: "good"//появилось новое свойство } } props: [ {prop1: "4"}//Добавляем в массив к a. ] } //вот что получиться должно: c: { car: "WW", detail:{ wheel: { left: "bad", right:"bad", center: "good" } }, props: [ {prop1: "1"}, {prop1: "2"}, {prop1: "3"}, {prop1: "4"} ] }; 

PS :
Without using any libraries.

    2 answers 2

    Like that?

     function extend(a, b){ for(var prop in b){ if(Object.prototype.toString.call(b[prop]) == '[object Array]' && Object.prototype.toString.call(a[prop]) == '[object Array]'){ // is array? a[prop] = a[prop].concat(b[prop]); } else { if(b[prop] === Object(b[prop]) && a[prop] === Object(a[prop])){ // is object? extend(a[prop], b[prop]); } else { a[prop] = b[prop]; } } } } 

    UPD: fixed incorrect work with arrays.

    • It looks beautiful, and, like, that is necessary. I'll try! - Anton Mukhin
    • 2
      . Object.prototype.toString.call (b [prop]) == '[object Array]' // well, is b [prop]. Constructor === Array // better? Besides, if it’s generally Orthodox, then it’s best to do something like this: if (! Array.isArray) {Array.isArray = function (v) {return v && v.constructor === Array}} Further in the code: (cap) Array.isArray (b [prop]); // well, and in my opinion, instead of b [prop] === Object (b [prop]) // all the same, the construction of the form b [prop] .constructor === Object - Zowie looks
    • xs, in general, Array.isArray already exists at the expense of b[prop].constructor === Object var func = function () {this.name = 'name'; } var obj = new func (); obj.constructor === Object; // fulse - Specter
    • ({fd: "qwe"} === Object ({fd: "qwe"})) - it will turn out false, always. But in general, the idea is clear to me, thank you. I accept the answer. - Anton Mukhin
    • Oh, you corrected the answer. So generally good. Thank! - Anton Mukhin

    If with jQuery, then everything is simple

     $.extend(true, obj1, obj2); 
    • one
      PS: Without using any libraries. , and additionally check how extend will work in the case of arrays and as required by the author - Grundy