SoFunction
Updated on 2025-04-03

Detailed explanation of Object value merging method in JavaScript

Preface:In daily development work, we may encounter the copying of all values ​​in objects in js, or it may be the setting merge problem faced during the revision of the client through electron development. Then this article will give a brief description of this solution.

Introduction: For example, with obj1 and obj2, we need to copy all values ​​in obj1 with the same depth as in obj2 to obj2, and we need to keep the obj2 field structure unchanged, and just call the method (using ES6 writing method).

Code:

/**
      * Copy the data in src into dist and keep the structure of dist
      * @param src
      * @param dist
      */
    copyValue(src, dist) {
      if (!src || typeof(src) !== 'object' || typeof(dist) !== 'object'){
        return ;
      }

      let keys = (dist)
      if (keys &&  > 0 && isNaN(keys[0])){
        (key => {
          let value = dist[key]
          let srcVal = src[key]

          // Determine whether it is an object. If it is, continue to traverse; if it is not, start assigning or ignoring          if (value !== undefined && typeof(value) === 'object' && srcVal && typeof(srcVal) === 'object' && srcVal[0] === undefined){
            copyValue(srcVal, value)
          } else if (value !== undefined && srcVal && typeof(value) == typeof (srcVal)){
            // If the source data exists and the types are the same, start assignment            dist[key] = src[key]
          }
        })
      }

    },

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.