What s wrong about arrays and objects?


#1

I have 2 issues about pushing a new object to an array and deleting a obejct from an array

this a piece of code of my program gruplar is an object array and each object has grupname,names and numbers
grupname field is a string
names field is an array
numbers field is an array

let a={grupname:this.data.title,names:this.data.names,numbers:this.data.numbers}
            this.gruplar.push(a)

when i add a new object,all objects’ names and numbers become as same as the new object’s names and numbers !!!

Why could this happen?

thanks in advance i couldnt figure out what s going on ?


#2

I knew I had come across this before, and lo and behold, it was you then too.


#3

OMG !!! this is so irritating issue. is this problem about ionic or typescript ?

Thanks a lot you enlighted me indeed


#4

Neither, really. It’s about JavaScript, which is the worst-designed language I have ever had to work with.


#5

the thing is that grupname is not affected only names and numbers .That is interesting too .

Thanks anyway i have to find an other solution .That issue killed my one week


#6

That’s because grupname is a primitive value. This issue affects only objects, because they are effectively copied and assigned by reference. And although I still we’re better off thinking of objects and arrays as completely separate beasts, this is one case where the fact that arrays are indeed objects at the bare-bones language level means that arrays are similarly affected. I still think lodash’s cloneDeep() should be your go-to option in cases like this.