JSON to JSON Copy based on Keys

This question already has an answer here:

  • How can I merge properties of two JavaScript objects dynamically? 55 answers

  • If you are not using jquery , do it as follows:

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

    if you are using jquery, it's simpler

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

    EDIT

    Based on PO's updated question, here is its updated solution to cover nested literals case

    FYA, In next solution, I'll assume that you don't use jQuery, as you didn't specify this in your question

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

    And here is a JSFiddle Sample click here

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

    上一篇: 如何扩展JavaScript对象?

    下一篇: JSON复制到JSON基于密钥复制