0

I have the following object in js :

let user = {name:"David",age:"23",address:{city:"Toronto",country:"Canada"}}

And, also, defined the following map object: let map = new Map()

How can i have a deep cloned object inside of the map?

amir tbi
  • 320
  • 2
  • 14

1 Answers1

-1

In this case, i think using Object.assign would be sufficient. This is because when you assign the shallow clone to the map, it creates a new reference for the address object.

let shallowClone = Object.assign({}, user);
map.set("David", shallowClone);

But if you really need a deep clone, as suggested:

const userCopy = JSON.parse(JSON.stringify(user));
map.set("David", clonedUser);

Additionally, Map object are used to make retrieving an item easier. For example, getting the user by the userName. But in your case, this would be problematic in case you have multiple users with the same name.