How to clone object in JavaScript?


I was trying to copy/clone the object and edit the new one but whenever I change edit NewObject, olderObject also get's changed, suppose here is my Object

    var OriginalObject= {
        "some": 2,
        "thing": [2, 3, 4, 5],
        "other": {
            "mymy": [60],
            "2": "asdfgret"
        };

How do I clone it, to edit and do the required changes, without affecting OriginalObject data?

I was copying it like 

var new_object= OriginalObject;

But it doesn't work.Any helpful link or code will work, thanks


Asked by:- jon
1
: 2275 At:- 5/25/2018 11:52:20 AM
Javascript clone object clone array







2 Answers
profileImage Answered by:- bhanu

You can directly copy a new object using assign  in javascript like below

var Cloned_new_object = Object.assign({}, OriginalObject);

// The "Cloned_new_object" variable now consists of all "Original_object" keys and values.
// Both variables are independent. Either one can be edited.

Or you can create own function like below

    function CopyObjectFunction(a) {
        // "use strict";
        // Un-comment the "use strict" directive statement if
        // this function is placed outside your own function.
        var result = {};
        var buff = [];
        var l;
        if (a.constructor === Object) { // check if the input is an Object type.
            buff = Object.keys(a); // get all keys of the input Object.
            l = buff.length; // the length of the keys (array now).
            if (l > 0) { // if the keys length greater than 0 (there's key found).
                buff.forEach(function (v) {
                    result[v] = a[v];
                });
            }
        }
        // the result.
        // if the input is an empty object, then the procedure above will be skipped.
        return result;
    }

and use it like below

var new_cloned_object = CopyObjectFunction(OriginalObject);

That's it, you are done.

3
At:- 5/26/2018 6:02:56 PM Updated at:- 5/26/2018 6:03:18 PM
Thanks for your proper answer 0
By : jon - at :- 5/30/2018 2:52:43 PM


profileImage Answered by:- vikas_jk

Method 1 using Object.assign for cloning object

Clone object using Javascript ES6 Object.assign method

var clone = Object.assign({}, obj);

Definition of object.assign : The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.

OR (Method 2,Custom function)

Create your JS function for cloning

function clone(obj) {
    if (obj === null || typeof (obj) !== 'object' || 'isActiveClone' in obj)
        return obj;

    if (obj instanceof Date)
        var temp = new obj.constructor(); //or new Date(obj);
    else
        var temp = obj.constructor();

    for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            obj['isActiveClone'] = null;
            temp[key] = clone(obj[key]);
            delete obj['isActiveClone'];
        }
    }
    return temp;
}

OR (Method 3)

Assuming your have only variables and not functions in object

var clonedObject = JSON.parse(JSON.stringify(oldObject));

Considering all of the above methods, I will prefer second method, but it doesn't have best performance.

Object.assign has better performance but it doesn't work for deep-clone.

Object.assign() also allows us to update or add new properties to the clone object.

For example, the consider copying marvel object, but at the same time update name property:

const marvel = {
  name: 'Thor',
  city: 'Asgard'
};
const marvelClone = Object.assign({}, hero, { name: 'Thor Clone' });
marvelClone; // { name: 'Thor Clone', city: 'Asgard' }

so, cloned object is created and have updated name as "Thor Clone".

1
At:- 3/9/2022 11:12:20 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use