0

I'd like to loop over an array of objects and another array to create a new array.

This.wholeWeek = [{test: "1"}, {test2: "2"}, {test3: "3"}]

This.courtData = [1, 2, 3]

As a result I would like to get:

[{test: "1", court: 1}, {test: "1", court: 2}, {test: "1", court: 3}, {test2: "2", court: 1}, {test2: "2", court: 2}, {test2: "2", court: 3}, {test3: "3", court: 1}, {test3: "3", court: 2}, {test3: "3", court: 3}]

Code:

this.courtTD = [];
for (let i = 0; i < this.wholeWeek.length; i++) {
  for (let s = 1; s <= this.courtData.length; s++) {
    const week = this.wholeWeek[i];
    week.court = s;
    this.courtTD.push(week);
  }
}

But my method gives me:

[{test: "1", court: 3}, {test: "1", court: 3}, {test: "1", court: 3}, {test2: "2", court: 3}, {test2: "2", court: 3}, {test2: "2", court: 3}, {test3: "3", court: 3}, {test3: "3", court: 3}, {test3: "3", court: 3}]

Every help is highly appreciated! Thank you!

Barmar
  • 741,623
  • 53
  • 500
  • 612
Devchris
  • 394
  • 3
  • 12

1 Answers1

1

Could you try this code:

let arr = [{test: "1"}, {test2: "2"}, {test3: "3"}];
let arr_1 = [1, 2, 3];
let result = [];

for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr_1.length; j++) {
            let obj = JSON.parse(JSON.stringify(arr[i])); // copy of object
            obj.court = arr_1[j];
            result.push(obj);
    }
}

You should make a copy of an object.