user1452893
user1452893

Reputation: 868

How do I get a value from this localStorage array to create a new var?

Here is the localStorage entry I want to use:

Key: file

Value: [{"id":"usethis","somethingelse":"otherstuff"}]

I want to create a var from id in the Value array so I can make an if that says:

var idvalue = ??? (...this is what I need help retrieving...)

if (idvalue == "usethis") { ...do some stuff... } else { ...do something else... }

Upvotes: 0

Views: 347

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

Try

//read the string value from localStorage
var string = localStorage.getItem('file');
//check if the local storage value exists
if (string) {
    //if exists then parse the string back to a array object and assign the first item in the array to a variable item
    var file = JSON.parse(string),
        item = file[0];
    //check whether item exists and its id is usethis
    if (item && item.id == "usethis") {} else {}
}

Upvotes: 1

Daniel Bank
Daniel Bank

Reputation: 3899

HTML5 Local Storage only handles string key/value pairs. To save your JSON object in Local Storage you will have to stringify it when you save it, and parse the string when you read it back. It is all explained very well in the following StackOverflow question Storing Objects in HTML5 localStorage.

Upvotes: 1

Related Questions