I'm currently working on a personal highscore feature for a Minesweeper implementation I'm doing in Vue.js 2.x (working demo).
As of now, I'm planning to create a single localStorage item for these personal records
localStorage.setItem('defuse-records', 'easy:121,medium:455,hard:781,insane:')
The numbers represent the seconds that it took the person to solve the different difficulty presets. In the example the person hasn't solved insane yet.
I would like to create an object from this string that looks like this:
{ easy: 121, medium: 455, hard: 781, insane: null }
This is what I've done so far:
getLocalRecords() {
let localRecords = localStorage.getItem('defuse-records')
if(!localRecords) {
return { easy: null, medium: null, hard: null, insane: null }
}
let strArray = localRecords.split(',')
let recordsObj = strArray.map(function (str) {
let rObj = {}
rObj[str.split(':')[0]] = str.split(':')[1] || null
return rObj
})
return recordsObj
}
However, due to the nature of Array.prototype.map, that returns an Array and not an Object:
[{ easy: 121}, { medium: 455 }, { hard: 781 }, { insane: null }]
Now I can of course iterate over this Array and create the object I want, but this feels complicated and I was hoping for someone to have a more elegant way of converting in both directions.
Maybe someone sees a solution immediately?
2nd question: Would there be a better suited, easier to use way to use a single storage item to store the personal records for all four difficulty levels?
JSON.parse?