迭代对象属性的Javascript方法

时间:2016-05-27 15:12:22

标签: javascript

我对使用哪种方法迭代对象的属性有疑问。

我有两个相同的对象。第一个对象是main,第二个对象是clone

有很多筑巢。我没有时间编写所有forfor inforEach循环,因为有很多嵌套。

如何从clone替换main的每个属性的值?这种方法是否已经存在?

1 个答案:

答案 0 :(得分:1)

你可以做那样的事情

function fillClone(source,target)
{
    if(typeof source == "array" && typeof target != "array")
       target = [];
    else if(typeof source == "object" && typeof target != "object")
       target = {};
    for (var i in source) {  
       if(typeof i == "object" || typeof i == "array")
          fillClone(source[i],target[i]);
       else
          target[i] = source[i];  
    }
    return target;
}