skip to Main Content

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?

3

Answers


  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.

    Login or Signup to reply.
  2. A very easy solution is to convert it into JSON and back:

    let user = {name:"David",age:"23",address:{city:"Toronto",country:"Canada"}};
    let userClone = JSON.parse(JSON.stringify(user));
    console.log(userClone);
    Login or Signup to reply.
  3. What about copying the user object before transforming it into the Map?

    const user = {
        name:"David",
        age:"23",
        address: {
            city:"Toronto",
            country:"Canada"
        }
    }
    
    const userCopy = JSON.parse(JSON.stringify(user));
    
    const map = new Map(Object.entries(userCopy));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search