Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate object multiple times based on array length - Angular 2+/ JavaScript

I have an object with empty values. I need to duplicate this object however many times the length of one of my arrays is. So then I would have two objects with the same properties but with different values.

TS

add = [
    {
      type: 'Package',
      value: ''
    }
]

this.form.value.packages = [1,2,3]

//This should duplicate the object based on length of packages

let packageDup = Array(this.form.value.packages.length).fill(this.add[0])

packageDup.forEach((res, i) => {

     packageDup[i].value = this.form.value.packages[i]

})

The issue with this method is that the values end up being the same. For instance, both object's value would be equal to 2. I feel like I'm overthinking this one. Thanks.

What I would like as a result ---

add = [
        {
          type: 'Package',
          value: '1'
        },
        {
          type: 'Package',
          value: '2'
        }, 
        {
          type: 'Package',
          value: '3'
        }
    ]
like image 483
userlkjsflkdsvm Avatar asked Sep 20 '25 03:09

userlkjsflkdsvm


1 Answers

To create a copy of the object 'obj', I usually use Object.assign({}, obj)

you could use something like this :

let packageDup = Array(this.form.value.packages.length)
    .fill(0) // needed to have some value and no empty value that would cause map to fail.
    .map(x => Object.assign({}, this.add[0]);

(as Daniel W Strimpel mentionned in his answer, be aware that it performs only a shallow copy, in case you have nested objects you should keep that in mind.)

let baseObject = { value: 1 }

let array = Array(3).fill(0).map(x => Object.assign({}, baseObject));

console.log(array);

array[1].value = 2;
array[2].value = 3;

console.log(array);
like image 115
Pac0 Avatar answered Sep 22 '25 16:09

Pac0