用于遍历JSON值的Javascript [英] Javascript for loop through JSON values

查看:57
本文介绍了用于遍历JSON值的Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json对象r:

I have a json object r:

[ { "id"     : "3443",
    "name"   : "Joe",
    "date1"  : "254",
    "date4"  : "261"
  },
  { "id"     : "50942",
    "name"   : "John",
    "date2"  : "192",
    "date4"  : "195"
  },
  { "id"     : "2524",
    "name"   : "Mary",
    "date1"  : "153",
    "date4"  : "163"
  }
]

,我希望有一个Java脚本For循环可以遍历dateX值. 我知道X在1到最大值之间.

and I wish to have a Javascript For loop to go through the dateX values. I know that X is between 1 and a Max value.

但是以下代码不起作用:

But following code does not work:

for (j=1; j<=Max; j=j+1)
{
  datestring = 'date' + j;
  if (isset(r[i].datestring)) value[j] = r[i].datestring;
  else value[j] = null; 
}


忘记解释我将isset函数定义为:


Forgot to explain that I defined the isset function as:

function isset(variable) {
     return typeof(variable) != "undefined" && variable !== null;
} 

推荐答案

首先使用普通的for循环遍历对象数组.然后使用for (var p in obj)遍历每个对象的属性,并检查p的值.像这样:

First iterate through the array of objects with an ordinary for loop. Then iterate through the properties of each object with for (var p in obj) and check the value of p. Something like:

for (var i = 0; i < arr.length; i++) {
    var obj = arr[i];

    for (var p in obj) {
        if (/^date\d+$/.test(p)) {
            var value = obj[p];
            // p is a dateX property name and value is the value
        }
    }
}

遍历所有可能的属性值以检查它们的存在是违反直觉的并且效率低下.相反,请遍历实际属性,并根据您的模式测试它们的名称.

It's counter-intuitive and inefficient to loop through all possible property values to check their existence. Instead, loop through the actual properties and test their names against your pattern.

这篇关于用于遍历JSON值的Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆