gregdevs
gregdevs

Reputation: 713

localStorage - looping through a value of a specific key in javascript

This might be tricky to explain, so I'll do my best.

I'm trying to use localstorage in a way, that im not even sure if its possible. Basically I want to submit some values as a list. When the user reloads, it pulls those values from the local storage and displays them.

Ideally, i wanted to store each value under the same Key and try and loop through that key and print the values associated with that key. As you can see when I reload, it's loading each letter in the array since its looking at the length of the entire value and not each word.

I know Im a bit off, but its about as far as I got. Would appreciate any hints (I've never worked with localStorage, so its a bit new to me)

consider this:

    var i = 0;
    var taskArray = [];
    var storedTasks = localStorage.getItem('Tasks');

  for( i = 0; i < localStorage.length; i++)
    $("#tasks").append("<li id='task-"+ i +"'>" + storedTasks[i] + "</li>");


     // Add a task
    $("#tasks-form").submit(function() {
        if ($("#task").val() != "") {
             $("#tasks").append("<li id='task-" + i + "'>"  + '<span class="taskSpan">' + $("#task").val() + '</span>' + '</li>')
            $("#task-" + i).css('display', 'none');
            $("#task-" + i).fadeIn(350);
            taskArray.push($("#task").val());
            localStorage.setItem('Tasks', taskArray);
            i++;

        }

        return false;
    });

JSFiddle

Upvotes: 2

Views: 1986

Answers (1)

jamesmortensen
jamesmortensen

Reputation: 34038

Regardless of the data type you push into localStorage, it all gets converted to a string in the end. This means that anything you pull out of localStorage must then be converted back to whatever data type you are expecting.

In this case, since you're working with a string, you're treating your iteration as one through an array of characters instead of an array of strings.

To convert back to an array, simply split on the ',' that separates each word:

var storedTasks = localStorage.getItem('Tasks');
var storedTasksArray = storedTasks.split(',');

Now, iterate through the storedTasksArray, and each index points to a word instead of a letter.

As an aside, to make your life less complicated, if you're going to use a lot of localStorage, you might consider doing a typeof value and storing the type in localStorage as well, then when you pull out the data, you have some metadata you can use to convert back to the data type prior to insertion.

Upvotes: 2

Related Questions