1

I'm new to javascript. Someone please show me how to store a map in local storage. Below is what I've tried. After storing I don't seem to be able to iterate the map keys. UDATE2: IT MIGHT BE THE serializeObject function. Why am I using this function? Otherwise when I post in AJAX, I get: Uncaught TypeError: Converting circular structure to JSON

UPDATE: LOOKS LIKE THE PROBLEM IS BEFORE IT EVER GOES INTO LOCAL STORAGE.

var reportId = getGUID();

var theReports = localStorage.getItem('reports');
if (theReports == null) {
    theReports = {};
}

theReports[reportId] = JSON.stringify($('#reportInfo').serializeObject());

// HERE ALSO I AM SEEING HUNDREDS OF FIELDS. I EXPECTED JUST reportID. I AM NOT SEEING THE KEY reportId. THIS IS BEFORE IT GOES INTO LOCAL STORAGE.

for (var prop in theReports)
{
   console.log(prop);
}

localStorage.setItem('reports', JSON.stringify(theReports));
var tReports = localStorage.getItem('reports');

// This prints out 1,2,3,...500 for every field in #reportInfo form 
// What I was expecting is reportId1, reportId2 etc. and definitely not the id of each field of the report itself!
for (var property in tReports) {
    if (tReports.hasOwnProperty(property)) {
        console.log(property);
    }
}

Here is the serializeObject function. Perhaps this is the problem.

$(function() {


  $.fn.serializeObject = function(){

  var self = this,
  json = {},
  push_counters = {},
  patterns = {
  "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
  "key":      /[a-zA-Z0-9_]+|(?=\[\])/g,
  "push":     /^$/,
  "fixed":    /^\d+$/,
  "named":    /^[a-zA-Z0-9_]+$/
  };


  this.build = function(base, key, value){
  base[key] = value;
  return base;
  };

  this.push_counter = function(key){
  if(push_counters[key] === undefined){
  push_counters[key] = 0;
  }
  return push_counters[key]++;
  };

  $.each($(this).serializeArray(), function(){

         // skip invalid keys
         if(!patterns.validate.test(this.name)){
         return;
         }

         var k,
         keys = this.name.match(patterns.key),
         merge = this.value,
         reverse_key = this.name;

         while((k = keys.pop()) !== undefined){

         // adjust reverse_key
         reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');

         // push
         if(k.match(patterns.push)){
         merge = self.build([], self.push_counter(reverse_key), merge);
         }

         // fixed
         else if(k.match(patterns.fixed)){
         merge = self.build([], k, merge);
         }

         // named
         else if(k.match(patterns.named)){
         merge = self.build({}, k, merge);
         }
         }

         json = $.extend(true, json, merge);
         });

  return json;
  };
  • Could you post the whole `tReports`? – bfavaretto May 24 '13 at 17:41
  • Basically I am saving off a form of several report fields. tRepports should point to theReports which was stored in localStorage. – MoreQuestionsThanAnswers May 24 '13 at 17:46
  • after setting theReports[reportId] = xyz, i thought that iterating theReports would give me property= reportId. – MoreQuestionsThanAnswers May 24 '13 at 17:47
  • you are still getting `theReports` out of the local storage. As Bart suggested. You have to use `JSON.parse()` to convert the string in an array. Otherwise `theReports` will also be a string and you are iterating over each letter. So change `var theReports = localStorage.getItem('reports');` to `var theReports = JSON.parse(localStorage.getItem('reports'));` – basilikum May 24 '13 at 18:34

3 Answers3

3

The for..in loop gives you only the keys and not the items itself. You get the items with tReports[property]

var obj = {
    "1": "one",
    "2": "two",
    "3": "three"
};

for (var key in obj) {
   console.log(key); //1, 2, 3
   console.log(obj[key]); //one, two, three
}
basilikum
  • 10,378
  • 5
  • 45
  • 58
  • I am not seeing the key. – MoreQuestionsThanAnswers May 24 '13 at 17:48
  • Well your line `console.log(property);` definitely prints the keys (property names) or indices (for arrays) of your object `tReports`. But i don't know what's inside of `tReports`. Based on what you wrote, it appeared that you're printing out indices of an array, when you actually want to print out the items of that array. – basilikum May 24 '13 at 17:58
  • @MoreQuestionsThanAnswers usually when people say `key` in this context, they are referring to property names. When you have a line such as `obj[foo] = bar`, `obj` is a hashmap, where `foo` is the `key` and `bar` is the `value`. – Geeky Guy May 24 '13 at 18:02
  • Right, but the problem is that I am seeing hundreds of keys. I just save one report and after that I see literally hundreds of keys even though I only set a few reports. – MoreQuestionsThanAnswers May 24 '13 at 18:10
  • Well, some other point of your code must be setting them. Try debugging it to see where the keys come from. – Geeky Guy May 24 '13 at 18:11
  • ok. I think it is the serializeObject method. Should I be using something else to serialize? – MoreQuestionsThanAnswers May 24 '13 at 18:15
  • If I don't use this method I get Uncaught TypeError: Converting circular structure to JSON – MoreQuestionsThanAnswers May 24 '13 at 18:22
  • I think that you should create a new question specifically for that. – Geeky Guy May 24 '13 at 18:25
1

Instead of:

console.log(property);

Do:

console.log(tReports[property]);

Since the property variable is the actual property name, not its value.

Geeky Guy
  • 9,229
  • 4
  • 42
  • 62
1
var tReports = localStorage.getItem('reports');

The variable tReports now holds the stringified version of the reports object.


The localStorage and sessionStorage only store a key/value pair as a string.

So if you wan't to store an object you need to serialize it to a string.

localStorage.setItem('key', JSON.stringify(myObject));

If you wan't to retrieve it from storage you need to deserialize it first before you can use it.

var myObject = JSON.parse(localStorage.getItem('key'));

https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Storage?redirectlocale=en-US&redirectslug=DOM%2FStorage

Bart
  • 17,070
  • 5
  • 61
  • 80