0

I have a multidimensional array consisting of objects which is made by using below function.

   function createEmptyArray() {
        const col = 10;
        const row = 9;
        let cellData = [];
        for (let i = 0; i < row; i++) {
            cellData.push([]);
            for (let j = 1; j <= col; j++) {
                cellData[i][j] ={
                    x:i,
                    y:j,
                    revealed :true,
                    flag :false,
                    containsMine :false,
                    surroundingMines :0
                }
            }
        }
        return cellData;
    }

const newArray= createEmptyArray();

How can I deep clone this. I know there are various ways like JSON.parse(JSON.stringify(o)) and $.extend(true, {}, o) but that creates many problems. JSON parsing method doesnot work when an object has a function.

Unity Hour
  • 550
  • 2
  • 7
  • 22
  • 3
    `JSON.parse` / `stringify` is *not* a framework. – CertainPerformance Jun 09 '18 at 03:25
  • you could look at the jquery source code to see what it does, underscore has similar function too ... but, *why re-invent the wheel* – Jaromanda X Jun 09 '18 at 03:26
  • @CertainPerformance sorry. – Unity Hour Jun 09 '18 at 03:29
  • You have lots of solutions [on this SO](https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge/48579540#48579540). Just apply one on each element of your array. (except Salakar's answer and alike) – RaphaMex Jun 09 '18 at 03:29
  • @JaromandaX I am using React for a project. And Jquery with React is an odd combination. – Unity Hour Jun 09 '18 at 03:30
  • I never said use jQuery ... I recommended investigating how it does what you want - though, as the first comment says, `JSON.*` are not part of a framework, they are *native* javascript functions - use them, save the hassle – Jaromanda X Jun 09 '18 at 03:33

2 Answers2

0

As I said in comments, deep clone topic is extensively covered in this SO.

However, since your objects in your array are flat, this can be handy for you:

const arrayCopy = newArray.map( (o) => Object.assign({},o) );
RaphaMex
  • 2,781
  • 1
  • 14
  • 30
0

You can use a library like underscore or lodash to use utility functions like this on objects and arrays. These functions are highly efficient, take care of corner cases (null, undefined, empty) and will save your time and as @Jaromanda said, why re-invent the wheel.

Jay Jodiwal
  • 121
  • 2
  • 10