0

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... }
Daniel Bank
  • 3,581
  • 3
  • 39
  • 50
user1452893
  • 838
  • 1
  • 11
  • 29

2 Answers2

1

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 {}
}
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

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.

Community
  • 1
  • 1
Daniel Bank
  • 3,581
  • 3
  • 39
  • 50