Home >Web Front-end >JS Tutorial >How to merge JS Object values

How to merge JS Object values

php中世界最好的语言
php中世界最好的语言Original
2018-04-14 09:14:372377browse

This time I will show you how to merge JS’s Object values, what are the precautions for JS’s Object value merging , the following is a practical case, let’s take a look.

Preface: In daily development work, we may encounter the copying of all values ​​​​in the object in js, or we may develop customers through electron On the other hand, we faced the problem of merging settings during the revision. So this article will give a brief solution to this problem.

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

Code:

/**
     * 将src中的数据copy到dist中,并保留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]
          // 判断是不是对象,如果是则继续遍历,不是则开始赋值或忽略
          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)){
            // 如果源数据存在,并且类型一致,则开始赋值
            dist[key] = src[key]
          }
        })
      }
    },

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the use of JS pseudo arrays

How does JS determine the client type

The above is the detailed content of How to merge JS Object values. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn