2013-03-04 76 views
1

假设有两个对象复制JavaScript对象到另一个对象,而不是创造新的属性

source = { 
    name: "A", 
    address: { 
     city: "B", 
     zipcode: "C" 
    }, 
    car: { 
     make: "D", 
     model: "E"  
    } 
}; 

target = { 
    name: "", 
    address: { 
     city: "" 
    } 
}; 

现在我想将复制源的所有数据到目标。但是,只有在目标中已存在相应的属性时才能进行复制。这是像jQuery的扩展,而不需要添加新的属性。有了上述数据,结果将是...

target = { 
    name: "A", 
    address: { 
     city: "B" 
    } 
}; 

这怎么能轻松实现?

回答

3

这应做到:

function extend(target, source) { 
    for (var prop in source) 
     if (prop in target) // <== test this 
      if (typeof target[prop] === "object") 
       extend(target[prop], source[prop]); 
      else 
       target[prop] = source[prop]; 
} 

免责声明:这个简单的一个不为数组,枚举原型属性,null值工作...

你不妨改变最外层循环到

for (var prop in target) 
     if (prop in source) 

取决于两个对象中的哪一个具有较少的枚举属性。

+0

我刚刚写完这个相同的答案! +1击败我。 – 2013-03-04 19:56:05

+0

非常感谢您的回答。 – mgs 2013-03-05 14:38:40

1

您可以循环访问target,然后从“源”中获取值。我会建议一个递归函数,因为你的对象可能有多个子对象。

function fill_in_values(target, source){ 
    for(var prop in target){ 
     if(typeof target[prop] === 'object'){ 
      fill_in_values(target[prop], source[prop]); 
     } 
     else{ 
      target[prop] = source[prop]; 
     } 
    } 
} 
相关问题