0

I'm trying to implement a method to copy dungeons in a game managment app.

Here is an example of a Dungeon to be copied:

attributes: { isReady: true, isMainQuest: true, color: "red", partyMax: 8 }
id: 59272
gamerMax: 12
gameId: 3
advLeveling: true
mainObjects: [0: "Treasure" 1: "BossKill"]
stats: { monsterCount: 25, treasureCount: 50, bossCount: 15 }

After reading a lot of posts about Object.keys, I decided to use that to "deep copy" my dungeon.

My latest interation simply looks like this:

Object.keys(obj).forEach(function (prop) {
        console.log("obj[prop]: ", obj[prop]);
}

But in all the versions I tried, including the one above, they never deep copy the nested arrays and objects like attributes, mainObjects, and stats.

Is there a way to copy those as well, no matter how deep?

Thanks!

SkyeBoniwell
  • 6,345
  • 12
  • 81
  • 185
  • 2
    Use `JSON.parse(JSON.stringify(object))` works all the time – Beshambher Chaukhwan May 03 '21 at 20:06
  • 1
    Does this answer your question? [What is the most efficient way to deep clone an object in JavaScript?](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – peter554 May 03 '21 at 20:16
  • 3
    JSON doesn't work with certain values, e.g. Date object, functions, so be careful. I'd use utility libraries such as `lodash` or similar. – Andrii Lukianenko May 03 '21 at 20:26

1 Answers1

2

You can use the spread operator in JavaScript.

In your case, it can be done by

const newObject = {...oldObject};

For more information read this blog https://medium.com/@kevinlai76/the-spread-operator-deep-and-shallow-copies-d193ac9b58bf

athul raj
  • 176
  • 1
  • 5