English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed explanation of the method of merging Object values in JavaScript

Main TextPreface:

In daily development work, we may encounter the task of copying all values in JavaScript objects, or it may be a setting merging problem faced when developing a client through electron and making revisions. This article will provide a brief description of a solution to this issue.1Introduction: For example, there is an obj2, obj1, we need to copy obj2All fields in the object that are the same as obj2, and it is necessary to maintain the same field at the same depth in obj2The field structure remains unchanged, you can call the method after that (using ES6Writing style).

Code:

/**
     * Copy the data from src to dist, while retaining the structure of dist
     * @param src
     * @param dist
     */
    copyValue(src, dist) {
      if (!src || typeof(src) !== 'object' || typeof(dist) !== 'object'){
        return ;
      }
      let keys = Object.keys(dist)
      if (keys && keys.length > 0 && isNaN(keys[0])){
        keys.forEach(key => {
          let value = dist[key]
          let srcVal = src[key]
          // Determine if it is an object, if it is, continue to traverse, if 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 consistent, then start assigning values
            dist[key] = src[key]
          }
        }
      }
    ,

That is all the content of this article, hoping it will be helpful to everyone's learning, and also hope that everyone will support the呐喊 tutorial more.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report violations, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You may also like