How to copy a 2d array of Objects in javascript — one line solution

Tengen Uzui
2 min readMay 28, 2021

When you’re trying to copy an 2d-array of objects with a common way like the spray operator, or using map over the all elements in the array never goin to work because the array still having references (if you don’t know what are references, i recommend this post ) to the another objects, so you need to copy the objects that are inside of each array and make a copy on each one, you can do it with this simple line.

Ok… You may ask, but was happening there?

First: We iterate over each element of the principal array with the ‘map’ function and we return each element in this case that element are arrays inside in of our principal array.

Second: We make a shallow copy of each array.

row.slice()

The method slice make a shallow copy, If you want to go deeper in your study, I invite you to review the documentation, here => Array.prototype.slice().

Third: That slice() return a copy of…. yeaaah an array! so we just need to make a copy of and simple Object. so lets do it.

row.slice().map((object2Copy) => Object.assign({}, object2Copy))

This map iterate over each child object of each element of our array and return a copy of that object.

If you never used Object.assign(), you can practice with this example and a look at the documentation never hurts, here => Object.assign().

Try this in your machine!

const person = {     
firstName: 'John',
lastName: 'Doe'
};
const personCopy = Object.assign({}, person);console.log(personCopy);

and that’s all!,If you have any questions, leave me a comment, email or a tweet, I hope I have helped you!

--

--

Tengen Uzui
0 Followers

Backend developer and Hashira.