Home  >  Article  >  Web Front-end  >  About how to merge Object values ​​in JavaScript

About how to merge Object values ​​in JavaScript

亚连
亚连Original
2018-06-19 09:48:201448browse

This article mainly introduces the Object value merging method in JavaScript in detail, which has certain reference value. Interested friends can refer to it

Foreword: In daily life During development work, we may encounter the copying of all values ​​​​in objects in js, or we may develop the client through electron, and face the problem of setting merging when revising. 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]
          }
        })
      }

    },

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to implement a calculator using JavaScript

How to implement table filtering using Angular

About how Vue.js implements infinite scrolling loading

Chrome Firefox comes with debugging tools for debugging (detailed tutorial)

How to use Write Ajax request function in JS

How to build vue using vue-cli webpack

How to control multiple scroll bars to scroll synchronously using JS

Webpack framework (master core technology)

How to use webpack express to achieve multi-page site development

The above is the detailed content of About how to merge Object values ​​in JavaScript. 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