How to merge two multi-layer nested objects with JS?

// objA ()
objA = {
    a:"",
    b:[],
    c:{
        c1: "",
        c2: [],
        c3: {
            c31:"",
            c32:[],
            c33:{}
        }
    }
}
// objBobjA
objB = {
    c:{
        c3:{
            c32:["apple"]
        }
    }
}

requires that the values in objB be assigned to objA and retain the structure of the complete objA

//  :
objC = {
    a:"",
    b:[],
    c:{
        c1: "",
        c2: [],
        c3: {
            c31:"",
            c32:["apple"],
            c33:{}
        }
    }
}

using the Object.assign () method to merge objects will cause some key values that are not in ObjB to be merged, resulting in the loss of structure and ObjA structure. How to deal with it?

May.13,2022

function MergeRecursive(obj1, obj2) {
  for (var p in obj2) {
    try {
      // Property in destination object set; update its value.
      if ( obj2[p].constructor==Object ) {
        obj1[p] = MergeRecursive(obj1[p], obj2[p]);
      } else {
        obj1[p] = obj2[p];
      }

    } catch(e) {
      // Property in destination object not set; create it and set its value.
      obj1[p] = obj2[p];
    }
  }

do not want to write a search directly, you can also customize the operation of the next array, this function is directly the latter overrides the former.

quoted from How can I merge properties of two JavaScript objects dynamically?

Menu