0

I'm experimenting with localStorage and am still learning how to access values within the object. I have successfully returned a bunch of objects within localStorage, and now I'm wondering how to turn these comma separated key, value pairs into a legible format. I have tried the replace method as well as looping through the object, but have had no luck. I'd really appreciate your help.

This is my localStorage output:

{"question":"How do you get close to the president?","your_answer":"buy him some chocolates","answer":"bribe your way in","check":false}{"question":"What is your code name?","your_answer":"John","answer":"Mikhalov","check":false}

I would like for it to look like this:

Question #1: blahblah 
Your Answer: blah
Check: Wrong


Question#2: ...

Attempt#1:

    if (counter == questions.length-1){
        output = ''

    for(var i =0; i < localStorage.length; i++){
        output += localStorage.getItem(localStorage.key(i)).replace(/"{"/g,"\r\n");
    }}

Attempt#2

    if (counter == questions.length-1){
        for (var key in localStorage){
            for (option in key){
                console.log(option)
            }
        }
    }
I Like
  • 1,711
  • 2
  • 27
  • 52
  • 1
    See `for (var key in localStorage){ console.log(key) }` and `for (var key in localStorage){ console.log(localStorage[key]) }` - this should give a clue. – user2864740 Nov 27 '16 at 22:22
  • why not post this as an answer @user2864740? – RizkiDPrast Nov 27 '16 at 22:38
  • Thanks. Do you know why this returns `undefined` in the console: for (var key in localStorage){ a = localStorage[key] console.log(a["question"]) } – I Like Nov 27 '16 at 23:16
  • @str4gut You should post your above question as a separate question. However, here's the answer anyway: Your console is a Read Eval Print Loop (REPL), which evaluates what you type in, and returns the last expression. Since the for-loop is a statement (and therefore doesn't return any value), the console returns undefined. – Kyle Lin Nov 28 '16 at 00:26
  • 1
    @st4rgut `a` refers to a string. This is because `localStorage[key]` returns a string. – user2864740 Nov 28 '16 at 19:36

1 Answers1

1
var obj = [{"question":"How do you get close to the president?","your_answer":"buy him some chocolates","answer":"bribe your way in","check":false},{"question":"What is your code name?","your_answer":"John","answer":"Mikhalov","check":false}];

obj[0].question;

convert into array.