Home > Web Front-end > JS Tutorial > Detailed explanation about Object value merging method in JavaScript

Detailed explanation about Object value merging method in JavaScript

小云云
Release: 2017-12-23 14:32:46
Original
1408 people have browsed it

This article mainly introduces the Object value merging method in JavaScript in detail. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.

Foreword: In daily development work, we may encounter the copying of all values ​​​​in objects in js, or we may develop clients through electron, and face the merge of settings when revising. question. 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 the same 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]
          }
        })
      }

    },
Copy after login

Related recommendations:

Detailed explanation of the use of two methods in regular and object in Java

Detailed explanation of usage examples of object.extend static method in Javascript

Interpretation of Object and param attributes in html

The above is the detailed content of Detailed explanation about Object value merging method in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template