I’m working on an application which consists of creating different scenes. Each scene is saved in JSON with attributes such as background image etc. Like this:
[
{
"sceneId": 0,
"scenesrc": { "path": "images/image.jpg" },
"scenename": "test",
"scenedescription": ""
},
{
"sceneId": 2,
"scenesrc": { "path": "images/image2.jpg" },
"scenename": "test",
"scenedescription": ""
}
]
Now I’m trying to make a function that duplicates one of the scenes, sets a new ID for the new scene, and push it back to the scenes array.
Here’s my code:
const getSceneById = (scenes, sceneId) => {
return scenes.find(scene => scene.sceneId === sceneId);
};
function duplicate(sceneId) {
let scenes = [{"sceneId":0,"scenesrc":{"path":"images/image.jpg"},"scenename":"test","scenedescription":""},{"sceneId":2,"scenesrc":{"path":"images/image2.jpg"},"scenename":"test","scenedescription":""}];
const scene = getSceneById(scenes, sceneId);
// variable for the duplicated scene
let newScene = scene;
newScene.sceneId = 0;
// make an id for new scene that is larger than any other id
for (let i = 0; i < scenes.length; i++) {
if (parseInt(scenes[i].sceneId) > Math.floor(newScene.sceneId)) {
newScene.sceneId = scenes[i].sceneId+1;
}
}
scenes.push(newScene);
}
duplicate(2);
The problem is that when I add a scene to a new variable and give it an ID, the original scene also gets a new ID. It seems like newScene.sceneId = 0 also sets the same ID to scene. After I run the code, this is how the scenes JSON looks like:
[
{
"sceneId": 0,
"scenesrc": { "path": "images/image.jpg" },
"scenename": "test",
"scenedescription": ""
},
{
"sceneId": 0,
"scenesrc": { "path": "images/image2.jpg" },
"scenename": "test",
"scenedescription": ""
},
{
"sceneId": 0,
"scenesrc": { "path": "images/image2.jpg" },
"scenename": "test",
"scenedescription": ""
}
]
How can I add scene to newScene, so I can change newScene without affecting scene?