0

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?

3
  • 4
    Why not simply JSON.parse ? Commented Jan 11, 2018 at 15:49
  • don't use map, use reduce. Commented Jan 11, 2018 at 15:49
  • 1
    I don't understand why this question is getting downvoted. Maybe those who did can elaborate on this? Commented Jan 11, 2018 at 15:50

3 Answers 3

2

You need to slightly modify your original item in order to use JSON parse which would be the simplest way I think

localStorage.setItem('defuse-records', '{"easy":121,"medium":455,"hard":781,"insane":null}');

Then you can do:

getLocalRecords(){
    return JSON.parse(localStorage.getItem('defuse-records') || '{"easy":null,"medium":null,"hard":null,"insane":null}');
    // {easy: 121, medium: 455, hard: 781, insane: null}
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can just use reduce for this task:

'easy:121,medium:455,hard:781,insane:'
    .split(",")
    .reduce((obj, item)=>{ 
        let [key, value] = item.split(':'); 
        obj[key] = +value || null; 
        return obj;
    }, {})
//evaluates to {easy: 121, medium: 455, hard: 781, insane: null}

Comments

1
 getLocalRecords(){
    const localRecords = localStorage.getItem('defuse-records').split(",");
    const result = {};
    for(const pair of localRecords){
       const [key, val] = pair.split(":");
       result[key] = +val;
    }
    return result;
 }

Or functional:

  getLocalRecords(){
    return Object.assign({}, ...localStorage.getItem('defuse-records').split(",").map(pair => (([key, val]) => ({[key]: val}))(pair.split(":"))));
 }

Or using reduce:

 getLocalRecords(){
   return localStorage.getItem('defuse-records')
         .split(",")
         .map(pair => pair.split(":"))
         .reduce((result, [key, val]) => {
             result[key] = val;
             return result;
         }, {});
 }

However i would rather simply use JSON.stringify & parse:

 function store(settings){
   localStorage.setItem('defuse-records', settings);
 }

 function load(){
    return JSON.parse(localStorage.getItem('defuse-records'));
 }

11 Comments

Not sure if +val returns null for empty string.
In your comment, you suggested using JSON.parse - which is the obvious approach I overlooked. With your second suggestion, can't I just go return { ...localStorage.getItem('defuse-records'). /*etc */ } ?
const s = ""; +s === null // false
+"" evaluates to 0
@connexo its spread into object assigns arguments, e.g. Object.assign({}, what, ever) and the arrays elements are objects. However just use either the last or the first solution, the others are just a beautifully ugly way
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.