Cloning the object in JavaScript [duplicate]

2019-03-04 03:00发布

This question already has an answer here:

Hi i have use the following code to create the object

var parent = {};
parent["Task name"] = "Task " + ++x;
parent["Start time"] = "01/03/2013";
parent["End time"] = "01/08/2013";
parent["Duration"] = "5 days";
parent["Status"] = Math.round(Math.random() * 100);

How to clone / take the copy of the object using JavaScript Code . Is there any other way to achieve this?

3条回答
混吃等死
2楼-- · 2019-03-04 03:11

Try this with jQuery:

var parent = {};
                parent["Task name"] = "Task " + ++x;
                parent["Start time"] = "01/03/2013";
                parent["End time"] = "01/08/2013";
                parent["Duration"] = "5 days";
                parent["Status"] = Math.round(Math.random() * 100);
var newObj = jQuery.extend(true, {}, parent);
查看更多
做个烂人
3楼-- · 2019-03-04 03:12

The simplest way to clone an object is using the following function:

function clone(a){var b=function(){};b.prototype=a;return new b;}

This creates a basic copy of the object, do note though that this does not create a deep copy, only a shallow one.

查看更多
叛逆
4楼-- · 2019-03-04 03:21

The most basic way is as follows :

var clone = {};
for (var k in parent) {
    clone[k] = parent[k];
}

Works in this case since all values are of primitive types.

查看更多
登录 后发表回答