如何将一个对象复制到另一个对象并在JavaScript中向新对象添加新字段?

时间:2016-05-02 17:28:35

标签: javascript jquery javascript-objects

我有一个这样的对象:

{"question": "", "options" : [{"subject": "", "teacher": "", "answer": [] } 
}

我想将此对象的数据复制到此:

{"question": "", "options" : [{"subject": "", "teacher": "", "new":" " } 
}

我想添加字段“new”而不是“answer”

2 个答案:

答案 0 :(得分:1)

深度克隆可以像这样实现:var b = JSON.parse(JSON.stringify(a));

请求的操作将是

var a = {"question": "", "options" : [{"subject": "", "teacher": "","answer": [] }}
var b = JSON.parse(JSON.stringify(a))
delete b.options[0].answer
b.options[0].new = 'your content'

答案 1 :(得分:0)

为了另一个答案......(虽然我很喜欢@lipp中的第一个)

这是一个深度克隆您的对象并切换键的 answer 键的函数。

问题这将取代任何回答,无论它在何处找到它。所以,如果你这样做:

clone({"question": "", "answer" : [{"subject": "", "teacher": "", "answer": [] ] } })

结果是

{"question": "", "new" : " " }
var toClone = {"question": "", "options" : [{"subject": "", "teacher": "", "answer": [] ] } };

function clone(original){   
    var copy;

    if (original instanceof Array) {
        copy = [];
        for (var i = 0, limit = original.length; i < limit; ++i) {
            copy[i] = clone(original[i]);
        }
    } else  if (original instanceof Object) { 
        copy = {};
        for (var key in original) {
            if( key === "answer" ){
                copy["new"] = " "; 
            } else
                copy[copiedKey ] = clone(original[key]);
        }
    } else
        copy = original;

    return copy;
}