0

I have something weird on the console.log in the Electron app, so basically it was the same as chromium does right?

Here's my code

let arr = [{
    actual_mix_class: 12,
    batch_id: "23498235025013",
    date: 1595416034349,
    days: [7, 7, 7, 14, 15, 28]
}]

let homeData = []

for (let i = 0; i < arr.length; i++) {
  for (let j = 0; j < arr[i].days.length; j++) {
    homeData[homeData.length] = arr[i]
    console.log(arr[i].days[j])
    homeData[homeData.length - 1].test_day = arr[i].days[j]
    console.log(homeData[homeData.length - 1])
    console.log(homeData[homeData.length - 1].test_day)
  }
}

I tried to separate days property into new arrays that has whole data inside object.

When I do console.log on test_day it was something not right on the display enter image description here

It displayed correct it was 14 until I expanded the console.log then displayed 28, and all test_day has same value 28.

Then finally I do console at the end after process finish

homeData.forEach(e => {
  console.log(e.test_day)
})

It said 28 six times.

Where I doing wrong here? Please help, thank you in advanced.

banguncool
  • 47
  • 7

1 Answers1

1

The problem is when you do homeData[homeData.length] = arr[i], you are actually assigning a reference of the original arr[i] to the homeData[homeData.length].

Then when you do homeData[homeData.length - 1].test_day = arr[i].days[j], you are again assigning a reference to an internal property of the above object to another field of the same object, making it a circular reference.

What you can do is to use spread syntax to make a copy of the arr[i], before assigning it to homeData[homeData.length] as below.

homeData[homeData.length] = {...arr[i]};

In case you are not using ES6, you can use Object.assign() as below.

Object.assign(newObj, arr[i]);
homeData[homeData.length] = newObj;
Udith Gunaratna
  • 2,091
  • 1
  • 13
  • 17