如何遍历对象的所有字段

时间:2013-05-24 17:39:18

标签: javascript

我是javascript的新手。有人请告诉我如何在本地存储中存储地图。以下是我尝试过的。存储后,我似乎无法迭代地图键。 UDATE2:它可能是serializeObject函数。           我为什么要使用这个功能?否则,当我在AJAX中发帖时,我得到:           未捕获的TypeError:将循环结构转换为JSON

更新:看看问题是否在进入本地存储之前。

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);
    }
}

这是serializeObject函数。也许这就是问题所在。

$(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;
  };

3 个答案:

答案 0 :(得分:2)

for..in循环只提供键而不是项目本身。您获得了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
}

答案 1 :(得分:1)

而不是:

console.log(property);

执行:

console.log(tReports[property]);

由于property变量是实际的属性名称,而不是其值。

答案 2 :(得分:1)

var tReports = localStorage.getItem('reports');

变量tReports现在保存报告对象的字符串化版本。


localStoragesessionStorage仅将键/值对存储为字符串。

因此,如果您不想存储对象,则需要将其序列化为字符串。

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

如果您不想从存储中检索它,则需要先将其反序列化,然后才能使用它。

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

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