-1

Trying to solve this question and having another question by myself instead.

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

Below is the chrome logging which is what I was expecting.

enter image description here

But when I logging the answer, below is the result instead:

enter image description here

For each of the iteration in arr[1]["Num_of_Floors"], clearly I printed the y value correctly and immediately construct the object and push into array but seems like value 1 has always been overwritten

Isaac
  • 12,042
  • 16
  • 52
  • 116

2 Answers2

0

You are not creating a new object on the second loop. You are just changing the value of newObj in the second loop that you created on the first loop.

You can do something like:

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

Or you can create the object and push at the same time:

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);
Eddie
  • 26,593
  • 6
  • 36
  • 58
0

Here, you're always overwriting the previous value:

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

So newObj["Num_of_Floors"] will only ever be equal to the last floor in the array after the end of the loop. It sounds like you want to make and push an object on each iteration instead:

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);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Hi @CertainPerformance, could you take a look at my question here: https://stackoverflow.com/q/75865618/1113598 – batman Mar 31 '23 at 10:32