JSON复制到JSON基于密钥复制

这个问题在这里已经有了答案:

  • 我如何动态合并两个JavaScript对象的属性? 55个答案

  • 如果你不使用jquery,按如下操作:

    function parseandmatchjson(json1, json2) {
    
        var combined_json = {};
    
        // Deep copy of json1 object literal
        for (var key in json1) {
            combined_json[key] = json1[key];
        }
    
        // Copy other values from json2
        for (var key in json2) {
            if (! json1.hasOwnProperty(key))
                combined_json[key] = json2[key];
        }
    
        return combined_json;
    }
    
    var json1 = {val1: 1, val2:2, val3:3};
    var json2 = {val1: 52, val2:56, val7: 7, val5: 5, val3:33};
    var json3 = parseandmatchjson(json1, json2);
    

    如果你正在使用jQuery,那就更简单了

    var json1 = {val1: 1, val2:2, val3:3};
    var json2 = {val1: 52, val2:56, val7: 7, val5: 5, val3:33};
    var json3 = $.extend({}, json2, json1);
    

    编辑

    基于采购订单的更新问题,这里是其更新的解决方案,以涵盖嵌套文字的情况

    FYA,在下一个解决方案中,我假设你不使用jQuery,因为你没有在你的问题中指定这个

    function parseandmatchjson(json1, json2) {
    
        // private function to traverse json objects recursively
        function traverse(object, callback) {
            for (var key in object) {
                // only return leaf nodes
                if((/boolean|number|string/).test(typeof object[key]))
                    callback.apply(this, [object, key, object[key]]);  
                // if not base condition, dig deeper in recursion
                if (object[key] !== null && typeof(object[key]) == "object")
                    traverse(object[key], callback);
            }
        }
    
        // create deep clone copy of json1
        var result = JSON.parse(JSON.stringify(json1));
    
        // create a flattened version of json2 for doing optimized lookups
        var flat_json2 = {};
        traverse(json2, function(object, key,value) {
            flat_json2[key] = value;
        });
    
        // overwrite values in results, if they exist in json2
        traverse(result, function(object, key, value) {
            if(typeof flat_json2[key] !== "undefined" )
                object[key] =  flat_json2[key];
        });
    
        return result;    
    }
    
    
    // Now, lets test it
    var json1 = {wrapper: {val1: 1, val2: 2}}
    var json2 = {val1: 'without wrapper'}
    var merged_json = parseandmatchjson(json1, json2); 
    
    // check the result with a simple alert
    alert(JSON.stringify(merged_json));
    

    这里是一个JSFiddle Sample点击这里

    链接地址: http://www.djcxy.com/p/27339.html

    上一篇: JSON to JSON Copy based on Keys

    下一篇: Merging two javascript objects into one?