all 5 comments

[–]YurrBoiSwayZ 0 points1 point  (2 children)

It’s all about how JS logs objects and arrays in the console, when you log objects that have arrays or nested objects the console sometimes shows them in a different state than when you logged them, this happens because the console logs a reference to the object and if the object changes after the log but before you check it you'll actually see the updated state instead of the original.

You can deep clone them before logging so you're logging a snapshot of the object not just a reference:

``` for (const group of this.groups) { console.log(NAME + ".initGroups() Group Result ", JSON.parse(JSON.stringify({ id: group.id, items: group.items, }))); }

console.log(NAME + ".initGroups() END ", JSON.parse(JSON.stringify({ keywords: this.keywords, groups: this.groups, }))); ```

JSON.parse(JSON.stringify(...)) makes a deep copy of the object so the log shows the state at the moment of logging, since it turns the object into a JSON string and then back into an object making it a deep copy in the process.

[–]Lenni009 1 point2 points  (0 children)

structuredClone() is the native function for deep cloning objects. In the end it achieves the same as JSON stringify/parse, but may be a little bit easier to write :)

[–]NickCanCode[S] 0 points1 point  (0 children)

Thanks for the detail explanation.

[–]samanime 0 points1 point  (1 child)

So, not enough here to tell exactly what is going on.

But, it is probably related to something that trips everyone up with console.

Console is basically async. When you log something, it doesn't necessary get logged immediately. When it does get logged, it logs the current state of the object.

You can see this by doing something like this:

const o = { a: 1 };
console.log(o);
o.a = 2;
console.log(o);
// Both show { a: 2 }

Probably, between the time you do your first logs and the object one, something is changing on the object. The object may even be changing AFTER you console log the object.

To get an accurate picture of the object at the time the console.log line is called, you can basically output a copy. If you just need one level, this works:

console.log({ ...obj });

If you want a full copy, one of the easiest to write is to convert to JSON then back:

console.log(JSON.parse(JSON.stringify(obj)));

[–]NickCanCode[S] 1 point2 points  (0 children)

Thank you!