zoukankan      html  css  js  c++  java
  • JavaScript通过递归合并JSON

    通过递归合并JSON:

     function mergeJSON(o, n) {
        let oType = Object.prototype.toString.call(o);
        let nType = Object.prototype.toString.call(n);
        if (nType == '[object Object]' && oType == '[object Object]') {
            //合并属性(object)
            for (let p in n) {
                if (n.hasOwnProperty(p) && !o.hasOwnProperty(p)) {
                    o[p] = n[p];
                } else if (n.hasOwnProperty(p) && (o.hasOwnProperty(p))) {
                    let oPType = Object.prototype.toString.call(o[p]);
                    let nPType = Object.prototype.toString.call(n[p]);
                    if ((nPType == '[object Object]' && oPType == '[object Object]') || (nPType == '[object Array]' && oPType == '[object Array]')) {
                        mergeJSON(o[p], n[p]);
                    } else {
                        o[p] = n[p];
                    }
                }
            }
        } else if (nType == '[object Array]' && oType == '[object Array]') {
            //合并属性(array)
            for (let i in n) {
                let oIType = Object.prototype.toString.call(o[i]);
                let nIType = Object.prototype.toString.call(n[i]);
                if ((nIType == '[object Object]' && oIType == '[object Object]') || (nIType == '[object Array]' && oIType == '[object Array]')) {
                    mergeJSON(o[i], n[i]);
                } else {
                    o[i] = n[i];
                }
            }
        }
    
        //合并属性(other)
        o = n;
    }
    
    //test
    
    let json1={
        "a": "json1", 
        "b": 123, 
        "c": {
            "dd": "json1 dd", 
            "ee": 556, 
            "f": "ff1"
        }, 
        "list": [
            {
                "a": 123, 
                "b": 96
            }, 
            {
                "a": 45, 
                "b": 56
            }
        ]
    };
    let json2={
    
        "a": "json2", 
        "a2": 369, 
        "c": {
            "dd2": "json2 dd", 
            "ee": "gg2"
        }, 
        "list": [
            {
                "a": "a1", 
                "b1": 69
            }, 
            369, 
            {
                "i3": 36
            }
        ]
    };
    
    mergeJSON(json1,json2);
    
    console.log(JSON.stringify(json1));
    

      

  • 相关阅读:
    几个工具类
    C#学习-程序集和反射
    Unity学习-鼠标的常用操作(八)
    Unity学习-碰撞检测(七)
    Unity学习-摄像机的使用(六)
    Unity学习-地形的设置(五)
    Unity学习-预制(四)
    Unity学习-元素类型(三)
    Unity学习-软件的基本操作(二)
    Unity学习-工具准备(一)
  • 原文地址:https://www.cnblogs.com/Sandheart/p/9627087.html
Copyright © 2011-2022 走看看