0

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

1 Answers1

0

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}.

Nico_
  • 1,388
  • 17
  • 31
  • ah that makes sense. but why does it print different values for b.key and b in the first (or more specifically, anything but the last) iteration? – Neel Kallidai Aug 30 '22 at 12:25
  • The `console.log` is not always reliable, specially in that kind of case for the exact same reason: https://stackoverflow.com/a/48969647/3672560. If you use `console.log(JSON.parse(JSON.stringify(b)))`, you'll get the right value. – Nico_ Aug 30 '22 at 12:33