如何通过类别prop分离从.getJSON呈现的项目

时间:2016-06-06 04:05:17

标签: javascript jquery json filtering

我有一个咖啡菜单,例如,每个咖啡都有自己的parentCategory,我想在页面上呈现它们,但我不完全确定从哪里开始:

  • 类别标题

    • 项目
    • 项目
    • 项目
    • 项目
  • 类别标题

    • 项目
    • 项目

我的数据模型如下所示:

{ "menuItems": [
	{
    "index": 0,
    "parentCategory": "Americanos", 
    "calories": 234,
    "name": "Caffè Americano",
    "photos": {
      "squareThumb": "http://www.starbucks.com/assets/67c30b9dacd4406db797b1690ac22475.jpg"
    }
  }, {
    "index": 0,
    "parentCategory": "Lattes", 
    "calories": 234,
    "name": "Caffè Latte",
    "photos": {
      "squareThumb": "http://www.starbucks.com/assets/aee68ca3048142f38741f20b30b7a581.jpg"
    }
  }, {
    "index": 0,
    "parentCategory": "Mochas", 
    "calories": 234,
    "name": "Caffè Mocha",
    "photos": {
      "squareThumb": "http://www.starbucks.com/assets/bc15a5ca9d744b66bda07254f2f50013.jpg"
    }
  }...

我当前的脚本如下:

$.getJSON('menu.json', function(drinks) {
  var getMenuItem  = drinks.menuItems;
  var sortedArray = getMenuItem.sort(function(a,b){
    return a.parentCategory > b.parentCategory ?1 :-1
  })
  var output = "";
  for (var i in sortedArray) {
      output += "<div class='menuItem'><p>" + drinks.menuItems[i].name + "</p><img src='" + drinks.menuItems[i].photos.squareThumb + "'/></div>";
  }
  document.getElementById("demo").innerHTML=output;
});

1 个答案:

答案 0 :(得分:0)

将最新类别保留在变量中。每当类别更改时,请为该类别开始新的<div>

var last_cat = null;
var output = "";
for (var i in sortedArray) {
    var item = sortedArray[i];
    if (item.parentCategory != last_cat) {
        if (last_cat) { // close the previous category
            output += "</div>";
        }
        output += "<div class='category'><p>" + item.parentCategory + "</p>";
        last_cat = item.parentCategory;
    }
    output += "<div class='menuItem'><p>" + item.name + "</p><img src='" + item.photos.squareThumb + "'/></div>";
}
if (last_cat) {
    output += "</div>";
}