jQuery:获取对象内部对象的成员计数

时间:2018-08-13 07:13:25

标签: jquery arrays json ajax object

我用json输出多维数组的PHP数据,如下所示(已简化):

// query for education
$q = "SELECT ID, name, surname, email FROM education WHERE age='$age'";
$r = mysql_query($q) or die(mysql_error());

$num_rows = mysql_num_rows($r);

$data = array();

if($num_rows > 0) {
    $rows_education = array();
    while ($row = mysql_fetch_assoc($r)) {
      $row_array['ID'] = $row['ID'];
      $row_array['name'] = $row['name'];
      $row_array['surname'] = $row['surname'];
      $row_array['email'] = $row['email'];
      array_push($rows_education, $row_array);
    }
  $data['success'] = true;
  $data['record']['computer'] = $rows_computer; // comes from another query
  $data['record']['education'] = $rows_education;
} else {
  $data['success'] = false;
}
header('Content-Type: application/json');
echo json_encode($data);

在客户端,我使用以下JS代码:

    function View(e) {
  $.ajax({
    type: "GET",
        url: "s_myfile.php?op=get",
        data : { 
          ID: e.data.record.ID
        },
        dataType: "json",
        success: function(j)
        {
          console.log(j);

          var c = Object.keys(j.record.education).length;
          alert(c);

        },
        error: function(data) {
          console.log(data);
        }
  });
}

我的问题是,Object.keys(j.record.education).length给我键的数量是4。但是我想获得用mysql_query ($num_rows)返回的行数,这是一个动态的结果。如何获取(记录)对象中的对象数量(教育)?

1 个答案:

答案 0 :(得分:0)

要遍历对象键,请使用Object.keys(ObjectToIterateThrough)。但是j.record.education的类型(可能)已经是数组,因此您可以直接访问长度:j.record.education.length

下面的示例说明了数组和对象之间的差异以及如何在两种类型下实现同一目的:

var myObject = {
    uuid_1: { prop1: 1, prop2: 2 },
    uuid_2: { prop1: 3, prop2: 4 },
};
var myArray = [
    { uuid: 1, prop1: 1, prop2:2 },
    { uuid: 2, prop1: 3, prop2:4 },
];
// Iterate through object:
Object.keys(myObject).forEach(key => console.log(key, myObj[key]) );
// Iterate through array:
myArray.forEach(item => console.log(item.uuid, item) );