Javascript推送两个for循环覆盖数组

时间:2018-12-13 02:42:05

标签: javascript loops push

我想遍历一个对象数组和另一个数组来创建一个新数组。

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

This.courtData = [1, 2, 3]

因此,我希望获得:

[{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}]

代码:

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);
  }
}

但是我的方法给了我:

[{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}]

我们非常感谢您的帮助!谢谢!

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

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);
    }
}

您应该复制一个对象。