如何在 JSON 数据中循环

How to Loop in JSON Data

本文关键字:循环 数据 JSON      更新时间:2023-09-26

>我有一个如下所示的 JSON 数据文件,我想将utility下的所有对象加载到表中,但我什至无法将第一行加载到表中!

你能看看这个,让我知道我做错了什么吗?以及我如何循环遍历所有utility对象并将它们加载到单独的表中<tr>

var data = {
  "utility": {
    "Water": {
      "account": "99999",
      "balance": "5555",
      "owner": "Fred"
    },
    "Phone": {
      "account": "7777",
      "balance": "6666",
      "owner": "Mark"
    },
    "Power": {
      "account": "A9885",
      "balance": "2222",
      "owner": "Suzan"
    }
  },
  "clients": {
    "David": {
      "account": "99999",
      "balance": "5555",
      "Date": "Jan 11"
    },
    "George": {
      "account": "7777",
      "balance": "6666",
      "Date": "March 22"
    },
    "Marco": {
      "account": "A9885",
      "balance": "2222",
      "Date": "Feb 25"
    }
  }
}
var obj = JSON.parse(data);
$(".container").append(
  '<table class="table table-hover"><tr><td>' + 
  obj.Water.account + 
  '</td><td>99999</td><td>5555</td><td>Fred</td></tr></table>'
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>

解析 JSON 后,它只是一个标准对象。按如下方式循环遍历它:

 // Loop through the utility property:
 for(var p in data.utility){
    // Loop through the properties of the utility property:
    for(var p2 in data.utility[p]){
        var row = document.createElement("tr");
        // Loop through the properties of the found property
        for(var p3 in data.utility[p][p2]){
            var cell - document.createElement("td");
            cell.innerHTML = p3 + " = " + data.utility[p][p2][p3];
        }
        row.appendChild(cell);
    }
    // Use appendChild to append row to table.
 }

希望这就是你想要的。告诉我您是否想要改进。

var data =
  {
    "utility": {
                 "Water": {
                  "account": "99999",
                  "balance": "5555",
                  "owner": "Fred" 
                },
                 "Phone": {
                  "account": "7777",
                  "balance": "6666",
                  "owner": "Mark" 
                },  
                  
                 "Power": {
                  "account": "A9885",
                  "balance": "2222",
                  "owner": "Suzan" 
                } 
    },
      
    "clients": {
                 "David": {
                  "account": "99999",
                  "balance": "5555",
                  "Date": "Jan 11" 
                },
                 "George": {
                  "account": "7777",
                  "balance": "6666",
                  "Date": "March 22" 
                },  
                  
                 "Marco": {
                  "account": "A9885",
                  "balance": "2222",
                  "Date": "Feb 25" 
                } 
    }
    
}
var utils = data.utility;
var tableStr='';
$.each(utils,function(key,value){
    tableStr +="<tr>";
    tableStr +="<td>"+key+"</td>";
    $.each(value,function(k,v){
      tableStr +="<td>"+k+"</td><td>"+v+"</td>";
    });
  tableStr +="</tr>";
});
$("#tbl").html(tableStr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <table  class="table table-hover" id="tbl">
    </table>
</div>

当你添加jQuery标签时,我为你提供了这种方法:

  //if you have a JSON (string)
  //var obj = JSON.parse(data);
  var prop1, prop2, inner,
      $table = $('<table>').addClass('table table-hover'),
      $tr, $td;
  //loop over 'utility' properties
  for (prop1 in data.utility) {
    $tr = $('<tr>');
    inner = data.utility[prop1];
    for (prop2 in inner) {
      $td = $('<td>').text(inner[prop2]).appendTo($tr);
    }
    $tr.appendTo($table);
  }
  $table.appendTo(".container");
如上所述

,您不需要解析数据。所以这个片段应该为你做:

//just use you data array you have above.
jQuery(document).ready(function(){
    var result = "<table>";
    for (var item in data.utility) {
        result += "<tr><td>" + item + ":</td>";
        console.log(item);
        for (var subItem in data.utility[item]) {
            result += "<td>" + data.utility[item][subItem] + "</td>";
        }
        result += "</tr>";
    }
    result+="</table>";
    jQuery(".container").append(result);
});

让我知道它是否适合您。

请阅读 MDN 的一篇文章,因为它描述了方法之间的差异:

  • 为。。在
  • 对象键
  • Object.getOwnPropertyNames
  • Object.getOwnPropertyDescriptors

另请查看方法:

  • 对象键()

Object.keys() 方法返回给定对象自己的可枚举属性的数组,其顺序与 for... in 循环(区别在于 for-in 循环也枚举原型链中的属性)。

来自 MDN 的例子:

var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']
// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
// array like object with random key ordering
var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(an_obj)); // console: ['2', '7', '100']
// getFoo is property which isn't enumerable
var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } });
my_obj.foo = 1;
console.log(Object.keys(my_obj)); // console: ['foo']
  • Object.getOwnPropertyNames()

Object.getOwnPropertyNames() 方法返回直接在给定对象上找到的所有属性(可枚举或不可枚举)的数组。

来自 MDN 的例子:

var arr = ['a', 'b', 'c'];
console.log(Object.getOwnPropertyNames(arr).sort()); 
// logs ["0", "1", "2", "length"]
// Array-like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.getOwnPropertyNames(obj).sort()); 
// logs ["0", "1", "2"]
// Logging property names and values using Array.forEach
Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) {
  console.log(val + ' -> ' + obj[val]);
});
// logs
// 0 -> a
// 1 -> b
// 2 -> c
// non-enumerable property
var my_obj = Object.create({}, {
  getFoo: {
    value: function() { return this.foo; },
    enumerable: false
  }
});
my_obj.foo = 1;
console.log(Object.getOwnPropertyNames(my_obj).sort()); 
// logs ["foo", "getFoo"]