Home > Software design >  Why does this loop repeatedly log the last pair in the array instead of all the pairs?
Why does this loop repeatedly log the last pair in the array instead of all the pairs?

Time:08-31

I am using Node v16.15.1 and TypeScript v4.7.4

I want to split an object into multiple objects, and then insert each object as a value in another object. i.e.

   {key1:"value1", key2:"value2"}
-> {key1:"value1"} and {key2:"value2"}
-> {key3:"value3", key4:"value4", key5:{key1:"value1"}} and {key3:"value3", key4:"value4", key5:{key2:"value2"}}

Below is the code I am using:

let a:any = {}
let entries = Object.entries({key1:"value1", key2:"value2"});
for(const el of entries) {
    let b = a;
    b.key = Object.fromEntries(new Map([el]));
    console.log(b.key);
    console.log(b)
}

However, the output I get is this. {key2:"value2"} is in both objects, instead of just the second one.


If I use the following code, however, I get the correct result:

let entries = Object.entries({key1:"value1", key2:"value2"});
for(const el of entries) {
  let b:any = {};
  b.key = Object.fromEntries(new Map([el]));
  console.log(b.key);
  console.log(b)
}

The problem with this is that I am not inserting into a blank object, and am passing it as a parameter in a function.

Why does this happen?

How would I be able to fix this?

TIA

CodePudding user response:

In javascript, when you do let a:any = {}; and then let b = a; you are assigning to b the references of a (not the value). So if you update b, you are actually updating a because both variable are the same.

If you want b to be a copy of a you should do something like : let b = {...a}.

  • Related