Skip to content

Deep clone array JavaScript | Example code

  • by

Use JSON parse/stringify or lodash library to Deep clone array in JavaScript. If you do not use Dates, functions, undefined, Infinity, [NaN], or other complex types within your object, a very simple one-liner to deep clone an object is.

JSON.parse(JSON.stringify(object))

Deep clone array JavaScript

Simple example code some of these will work with JSON.parse() followed by JSON.stringify().

<!DOCTYPE html>
<html>
<body>
  <script>

    const sampleObject = {
      string: 'string',
      number: 123,
      boolean: false,
      null: null,
      notANumber: NaN, // lost
      date: new Date('1999-12-31T23:59:59'),  // stringified
      undefined: undefined,  // lost
      infinity: Infinity,  // lost
      regExp: /.*/, // lost
    }

    const faultyClone = JSON.parse(JSON.stringify(sampleObject))

    console.log(faultyClone)
  </script>
</body>
</html> 

Output:

Deep clone array JavaScript

Deep copy with lodash

This is the most common way and easy-to-use JavaScript developers make a deep copy.

var myObj = {
  arr: [1, 2, 3],
  obj: {
    first: 'foo'
  }
}

var myDeepClone = _.cloneDeep(myObj)
var myShallowClone = _.clone(myObj)

Read more: https://lodash.com/docs/4.17.15#cloneDeep

How to deep copy an array containing nested objects, arrays & functions?

Answer: The shortest way is to use Json parse to copy objects and arrays.

var note2 = JSON.parse(JSON.stringify(notes))

but it didn’t copy functions, so check. You can use the solution below or just import Lodash and use this https://lodash.com/docs/#cloneDeep

<script>
    notes=[
    {
      contents: "Hello World 1",
      function: console.log,
      children: [
      {
        contents: "Hello World A",
        function: console.log,
        children: []
      },
      ]
    },
    {
      contents: "Hello World 2",
      function: console.log,
      children: []
    }
    ]

    function deepCopy(src) {
      let target = Array.isArray(src) ? [] : {};
      for (let key in src) {
        let v = src[key];
        if (v) {
          if (typeof v === "object") {
            target[key] = deepCopy(v);
          } else {
            target[key] = v;
          }
        } else {
          target[key] = v;
        }
      }

      return target;
    }
    console.log(deepCopy(notes))
</script>

Output:

[ { contents: 'Hello World 1',
    function: [Function: bound consoleCall],
    children: [ [Object] ] },
  { contents: 'Hello World 2',
    function: [Function: bound consoleCall],
    children: [] } ]

Do comment if you have any doubts or suggestions about this Js array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *