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));
    

      

  • 相关阅读:
    YUI+Ant 实现JS CSS压缩
    13.QT-QMainWindow组件使用
    12.QT4.7.4-解决WIN平台和Linux平台中文乱码,QLineEdit右击菜单中文显示
    11.QT-布局管理器(Box,Grid,Form,Stacked)
    10.QT-定时器
    9.QT-标准对话框
    8.QT-对话框(模态与非模态)
    7.QT-Qt对象间的父子关系
    6.QT-简易计算器实现(详解)
    5.QT-QString类
  • 原文地址:https://www.cnblogs.com/Sandheart/p/9627087.html
Copyright © 2011-2022 走看看