Array of object references array 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}];

Then I ran the following code and tried groupsOfItems[0].sample[0].a = 10, groupsOfItems[0].sample[0].a, groupsOfItems[1].sample[0].aand groupsOfItems[2].sample[0].achange it to 10.

How to 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>
Run codeHide result
+4
source share
3 answers

You need to clone the object before adjusting its referee to the array property

Replace

item.sample = sample;

with

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

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

+6
source

as indicated in this post

for(let i = 0; i < 10; i++) {
        var item = {};
        item.sample = $.extend(true, [], sample);
        groupsOfItems.push(item);
    }
0
source

. . .

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

var Item = function(a, b, c) {
  this.a = a;
  this.b = b;
  this.c = c;
}

for (let i = 0; i < 10; i++) {
  var item = {};
  item.sample = _.map(sample, function(item) {
    return new Item(item.a, item.b, item.c)
  });
  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);
//10 1 1

Thus, you assign them the entire container for your modifications, and the cloning problem goes away.

0
source

All Articles