Reputation: 2751
I'm having a difficult time with something that should be (and probably is) pretty basic. I have a constructor as follows:
function search_table(v1, v2, v3) {
this.field = v1;
this.condition = v2;
this.value = v3;
}
My application has an array of search_table which gets JSON.stringify
(ied) and then stored in localStorage.
My question is... when I retrieve the object from localStorage, it's in JSON string format. How do I get it back into the search_table[] format?
I'd prefer to do this without jQuery if possible. Thanks
I've tried to use something like the following:
var search_array = JSON.parse(string_val);
But it doesn't allow me to access search_array[i].condition
as an example.
Upvotes: 2
Views: 7371
Reputation: 28687
This should work. The following code:
function search_table(v1, v2, v3) {
this.field = v1;
this.condition = v2;
this.value = v3;
}
var arr = [new search_table(1, 2, 3), new search_table(4, 5, 6), new search_table(7, 8, 9)];
var str = JSON.stringify(arr);
console.log("stingified: ", str);
var search_array = JSON.parse(str);
var result = search_array[1].condition;
console.log("result: ", result);
Gives the following output:
stingified: [{"field":1,"condition":2,"value":3},{"field":4,"condition":5,"value":6},{"field":7,"condition":8,"value":9}]
result: 5
Your issue is elsewhere in the code that you haven't included here.
I'd also check Travis's suggestion - does your browser have native support for the JSON functions? Try these, and make sure they don't return "undefined":
alert(JSON.stringify);
alert(JSON.parse);
Also, make sure you initialized i
, and that it is in-bounds of your array.
Upvotes: 2