递归更新Javascript对象

时间:2013-05-05 11:59:46

标签: javascript json recursion

我有一个嵌套对象,我想用对象提供的值来更新它,该对象包含类似的结构,但只包含我想要更新的属性。创建新结果而不是修改初始对象也很棒。

    var initial = 
      { 
         a: 1, 
         b : { 
            c : 2, 
            d : 3 
         },
         f: 5 
      }; 

    var update = {
        a: 2,
        b: {
           d: 2
        }
    };         
    function updateFunction (a,b) {  return a+b;};
    var result= 
      { 
         a: 3, // updateFunction (1,2)=> 3
         b : { 
            c : 2, 
            d :5 // updateFunction (3,2) => 5
         },
         f: 5 
      };  

2 个答案:

答案 0 :(得分:3)

我是这样做的:

// The parallel to Array.map
Object.map = function(obj, f) {
    var result = {};
    for(k in obj)
        if({}.hasOwnProperty.call(obj, k))
            result[k] = f(k, obj[k]);
    return result;
}

// Takes two objects and uses `resolve` to merge them
function merge(a, b, resolve) {
    return Object.map(a, function(k, a_value) {
        if(k in b)
            return resolve(a_value, b[k]);
        else
            return a_value;
    });
}

// same as above, but recursing when an object is found
function recursive_merge(a, b, resolve) {
    return merge(a, b, function(a_value, b_value) {
        if(typeof a_value == 'object' && typeof b_value == 'object')
            return recursive_merge(a_value, b_value, resolve);
        else
            return resolve(a_value, b_value);
    });
}

result = recursive_merge(initial, update, function(a, b) { return a + b; })

答案 1 :(得分:2)

没有完全测试,但也许,

假设对象很简单,

function updateFunction (a,b) {  return a + b;};    

function recurse(initial, update){
    for(prop in initial){
        if({}.hasOwnProperty.call(initial, prop) && {}.hasOwnProperty.call(update, prop)){
            if(typeof initial[prop] === 'object' && typeof update[prop] === 'object'){
                recurse(initial[prop], update[prop]);
            }
            else{
                initial[prop] = updateFunction(initial[prop], update[prop]);
            }
        }
    }
}
recurse(initial, update);

修改

如果预期结果而不更改初始

function updateFunction (a,b) {  return a + b;};

function recurse(initial, update){
    var result = {};
    for(prop in initial){
        if({}.hasOwnProperty.call(initial, prop)){
            result[prop] = initial[prop];    
            if({}.hasOwnProperty.call(update, prop)){
                if(typeof initial[prop] === 'object' && typeof update[prop] === 'object'){
                    result[prop] = recurse(initial[prop], update[prop]);
                }
                else{
                    result[prop] = updateFunction(initial[prop], update[prop]);
                }
            }
        }    
    }
    return result;
}
var result = recurse(initial, update);

希望这会有所帮助。