2

Hi im aware this subject has been covered in previous posts, but im still not getting the result i need. Im trying to do a copy of an array of objects that that will be its own version of its original, and not affect each others data when changes are made. So far copying an array of ints works fine when i use slice() but not for vector of objects. It was mentioned in another post that slice() on vector of objects will still reference the objects, so is there a way to do it by value only??? Thanks.

property var array: new Array


Rectangle{id: ob1; width:50; height:50; color: "red"; property int num: 1}
Rectangle{id: ob2; width:50; height:50; x: 50; color: "blue"; property int  num: 2}
Rectangle{id: ob3; width:50; height:50; x: 100; color: "green"; property int num: 3}

Component.onCompleted: {

    array.push(ob1)
    array.push(ob2)
    array.push(ob3)

    var array2 = array //slice() will not work here

    array[1].num = 1111  //change made to first array NOT intended for second


    for(var i = 0; i < array.length; i++){
        console.log(array2[i].num)  //print out from second array still shows changes to first...
    }
}
LeeH
  • 55
  • 13

2 Answers2

1

You can do something like this:

var copyOfValues = listOfValues.map(function (value) {
    return $.extend({}, value);
});
Rafael Teles
  • 2,708
  • 2
  • 16
  • 32
  • 2
    I think that since they didn't mention jQuery, you should `return Object.assign({}, value)` instead, otherwise this is the correct answer (`map`) – Rob M. Aug 05 '16 at 18:02
  • Hi @RobM. yeah you are right, and by the way I didn't knew about Object.assign({}, value), thanks =) – Rafael Teles Aug 05 '16 at 18:04
0

Are you sure array.slice(0) wont work? If not try this:

var array2 = JSON.parse(JSON.stringify(array));
Runner
  • 246
  • 2
  • 9
  • Hi tried splice() before dosen't work on objects. The JSON line gives type error... – LeeH Aug 05 '16 at 18:17