I am making an application in which the user has the ability to add, remove, and edit JSON data through DOM interaction. I have created a working JavaScript-only prototype that accepts certain variables to manipulate certain elements of the JSON data, although it is rather messy and seems rather impossible for me to implement with the DOM.
Right now, my current structure is:
- Example Modding Session
- Modding Section
- A mod
- A mod
- Another Modding Section
- A mod
- A mod
- A mod
- Another Modding Session
- Modding Section
- Another mod
- Another mod
- Another mod
- Modding Section
- Another mod
Which has worked fine for me, however, my functions are very repetitive, which I would like to fix.
var addSession = function(sessionName) {
var selfSessionName = sessionName || undefined;
if(!selfSessionName) return;
moddingSessions.push({
"name": selfSessionName,
"sections": []
});
}
Here you may start to see a pattern:
var addSection = function(sectionName, sessionName) {
var selfSessionName = sessionName || undefined,
selfSectionName = sectionName || undefined;
if(!selfSectionName || !selfSectionName) return;
for(var i = 0; i < moddingSessions.length; i++) {
if(moddingSessions[i].name === selfSessionName) {
moddingSessions[i].sections.push({
"name": selfSectionName,
"mods": []
});
}
}
}
And here:
var addMod = function(modContent, sectionName, sessionName) {
var selfSessionName = sessionName || undefined,
selfSectionName = sectionName || undefined,
selfModContent = modContent || undefined;
if(!selfModContent || !selfSectionName || !selfSectionName) return;
for(var i = 0; i < moddingSessions.length; i++) {
if(moddingSessions[i].name === selfSessionName) {
for(var j = 0; j < moddingSessions[i].sections.length; j++) {
if(moddingSessions[i].sections[j].name === selfSectionName) {
moddingSessions[i].sections[j].mods.push(modContent);
}
}
}
}
}
As you can see, it works, but isn't very effective. I also have no idea how to handle each and every parameter when using this with DOM interaction. I hope there is a better way to achieve the same functionality.