Jaseem Abbas Jaseem Abbas - 7 months ago 14
Javascript Question

Array of array of objects reference in Javascript

I have an array as follows

var sample = [{a:1, b: 1, c:1}, {a:1, b: 1, c:1}, {a:1, b: 1, c:1}];


I then run the following code and try
groupsOfItems[0].sample[0].a = 10
,
groupsOfItems[0].sample[0].a
,
groupsOfItems[1].sample[0].a
and
groupsOfItems[2].sample[0].a
get changed to 10.

How do I prevent this?



var sample = [{a:1, b: 1, c:1}, {a:1, b: 1, c:1}, {a:1, b: 1, c:1}];


var groupsOfItems = [];

for(let i = 0; i < 10; i++) {
var item = {};
item.sample = _.clone(sample);
groupsOfItems.push(item);
}



groupsOfItems[0].sample[0].a = 10

console.log(groupsOfItems[0].sample[0].a,groupsOfItems[1].sample[0].a,groupsOfItems[2].sample[0].a);

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>




Answer

You need to clone the object before assiging its referece to the array's property

Replace

item.sample = sample;

with

item.sample = JSON.parse(JSON.stringify(sample));

Note that this method of cloning will be less efficient when the sample object grows. Try some other methods shown here.