对象值在forEach循环中被覆盖

时间:2018-06-20 04:03:20

标签: javascript arrays

试图解决这个question,而我自己一个问题。

let arr = [
  {"Footprint_Shape":["L-Shape","H-Shape","T-Shape"]},
  {"Num_of_Floors":[1,2]}
]

let answer = [];

arr[0]["Footprint_Shape"].forEach(x => {
  console.log('x: ',x)  //Keeping loop on first array, print the element
  let newObj = {};
  newObj["Footprint_Shape"] = x;

  arr[1]["Num_of_Floors"].forEach(y => {
    console.log('y: ',y)
    newObj["Num_of_Floors"] = y
    answer.push(newObj);
  })
});

console.log(answer);

下面是我期望的Chrome日志记录。

enter image description here

但是当我记录答案时,下面是结果:

enter image description here

对于arr[1]["Num_of_Floors"]中的每个迭代,显然我正确地打印了y值并立即构造该对象并将其压入数组,但是值1似乎一直被覆盖

2 个答案:

答案 0 :(得分:0)

您没有在第二个循环上创建新对象。您只是在第一个循环中创建的第二个循环中更改newObj的值。

您可以执行以下操作:

let arr = [{"Footprint_Shape": ["L-Shape", "H-Shape", "T-Shape"]},{"Num_of_Floors": [1, 2]}];

let answer = [];
arr[0]["Footprint_Shape"].forEach(x => {
  arr[1]["Num_of_Floors"].forEach(y => {
    let newObj = {};                      //You have to initate the object inside to create a new object every loop.
    newObj["Footprint_Shape"] = x;
    newObj["Num_of_Floors"] = y
    answer.push(newObj);
  });
});

console.log(answer);

或者您可以创建对象并同时推送:

let arr = [{"Footprint_Shape": ["L-Shape", "H-Shape", "T-Shape"]},{"Num_of_Floors": [1, 2]}];

let answer = [];
arr[0]["Footprint_Shape"].forEach(x => {
  arr[1]["Num_of_Floors"].forEach(y => {
    answer.push({Footprint_Shape: x, Num_of_Floors: y});   //Create and push
  });
});

console.log(answer);

答案 1 :(得分:0)

在这里,您总是覆盖以前的值:

arr[1]["Num_of_Floors"].forEach(y => newObj["Num_of_Floors"] = y

因此newObj["Num_of_Floors"]将永远等于循环结束后数组的最后一层。听起来好像您想在每次迭代中创建并推送一个对象:

let arr = [
  {"Footprint_Shape":["L-Shape","H-Shape","T-Shape"]},
  {"Num_of_Floors":[1,2]}
]
let answer = [];

arr[0]["Footprint_Shape"].forEach(Footprint_Shape => {
  arr[1]["Num_of_Floors"].forEach(Num_of_Floors => {
    answer.push({
      Footprint_Shape,
      Num_of_Floors,
    });
  })
});

console.log(answer);