循环使用JSON数据生成HTML

时间:2016-01-20 18:43:54

标签: javascript html json

我的JSON数据如下所示:

$Property = get-mailboxpermission -Identity $Mailbox -User $User | format-list AccessRights
if($Property -eq "AccessRights : {FullAccess}")
    {$PermissionText.AppendText("Full Access")}
if($Property -eq "AccessRights : {ReadAccess}")
    {$PermissionText.AppendText("Read Only")}

我正在使用此数据生成HTML,因此它看起来格式正确并且易于用户阅读。我这样做的方法是创建一个for循环来阅读网球和篮球类别。例如:

data = {
  "tennis": [{
    "Description": "Insert description here.",
    "Price": 379.99,
    "ProductName": "Babolat Play Pure Drive",
  }, {
    "Description": "Insert description here.",
    "Price": 199.99,
    "ProductName": "Yonex AI 98 Tennis Racquet",
  }],
  "basketball": [{
    "Description": "Insert description here.",
    "Price": 64.99,
    "ProductName": "Wilson NCAA Solution Official Game Basketball",
  }, {
    "Description": "Insert description here.",
    "Price": 59.99,
    "ProductName": "Spalding NBA NeverFlat Size 7 Composite Leather Basketball",
  }]
}

如何创建一个可以读取两个(或多个)类别的for循环?

以下是我在这个JSFiddle中的工作示例: https://jsfiddle.net/dsk1279b/1

3 个答案:

答案 0 :(得分:7)

双循环,一个迭代对象属性,下一个迭代数组:

for (var key in data) {
    for (var i = 0; i < data[key].length; i++) {
        //HTML logic
    }
}

您的小提琴已更新:https://jsfiddle.net/dsk1279b/4/

最终代码:

for (var key in data) {
    for (var i = 0; i < data[key].length; i++) {
        var title = data[key][i].ProductName;
        var desc = data[key][i].Description;
        var price = data[key][i].Price;
        var badge = document.createElement('div');
        badge.className = 'badge';
        badge.innerHTML =
            '<h1>' + title + '</h1>' +
            '<h2>' + desc + '</h1>' +
            '<div class="options-only-phone">' +
            '<a class="service-provider-call" href="#" target="_blank"> Buy for $' + price + '</a>';
        //I gave the div the same ID's as the keys in the object for ease
        document.getElementById(key).appendChild(badge);
    }
}

答案 1 :(得分:0)

tymeJV有一个很好的方法,但这可以更容易。

for(var product in data) {
    // logic
}

如果你查看你的数据,你有一个我们已经以键/值形式迭代的对象。 由于每个键都有项目数组,因此可以使用Array.forEach()函数。

for(var product in data) {
    // current is the current object in the array
    data[product].forEach(function(current){
        //HTML logic
    })
}

您更改了附加html模板的位置,因此我建议您将数据对象更新为:

data = {
  "tennis": {
    "products: [
        {
            "Description": "Insert description here.",
            "Price": 379.99,
            "ProductName": "Babolat Play Pure Drive"
        }, 
        {
            "Description": "Insert description here.",
            "Price": 199.99,
            "ProductName": "Yonex AI 98 Tennis Racquet"
        }
    ],
    "templateTarget": '#tennis-products-list'
  }
  "basketball": 
    "products":  [
        {
            "Description": "Insert description here.",
            "Price": 64.99,
            "ProductName": "Wilson NCAA Solution Official Game Basketball"
        }, 
        {
            "Description": "Insert description here.",
            "Price": 59.99,
            "ProductName": "Spalding NBA NeverFlat Size 7 Composite Leather Basketball"
        }
    ],
      "templateTarget": '#basketball-products-list'
}

这样的事情可以让你这样做:

for(var product in data) {
    // current is the current object in the array
    product.forEach(function(current){
        var badge = document.createElement('div');
        badge.className = 'badge';
        badge.innerHTML =
          '<h1>' + current.productName + '</h1>' +
          '<h2>' + current.description + '</h1>' +
          '<div class="options-only-phone">' +
          '<a class="service-provider-call" href="#" target="_blank"> Buy for $' + current.price +  '</a>';
        document.getElementById(current.templateTarget).appendChild(badge);
    })
}

这可以通过将{html字符串隐藏在script标签中隐藏type="text/x-template"(因为浏览器忽略它不理解的脚本类型)并使用innerHTML函数抓取它来进一步优化引用脚本标记上的id属性。

希望有所帮助!

答案 2 :(得分:0)

将数据展平为单个数组,其中category为属性:

var _data = Object.keys(data).reduce(
              (m,c) => m.concat(data[c].map(
                (i) => (i.category = c) && i))
           , []);

console.log(_data);

为UI使用扁平数组:

_data.forEach((d) => {
  var badge = document.createElement('div');
  badge.className = 'badge';
  badge.innerHTML = [
    '<h1>',
    d.ProductName,
    '</h1><h2>',
    d.Description,
    '</h1><div class="options-only-phone">',
    '<a class="service-provider-call" href="#" target="_blank"> Buy for $',
    d.Price,
    '</a>'].join('');
  document.getElementById(d.category + '-products-list').appendChild(badge);
})

https://jsfiddle.net/dsk1279b/11/