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
0
: 202 At:- 5/25/2018 11:52:20 AM
Javascript clone object clone array






1 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





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

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly