有没有更好的方法来检查类别是否已被迭代?

时间:2015-02-21 00:06:05

标签: javascript arrays json

目前,我检查类别ID是否存在,如果id为null,则会显示一个类别,document.write。有没有办法在不使用id的情况下只编写一次类别?

这是JSON:

var foods = { 
"category":{
    "Meats":[
        {
            "product":"NY Strip",
            "price":20.00,
            "cost":14.00,
            "total sold": 3
        },
        {
            "product":"Ribeye",
            "price":20.00,
            "cost":14.00,
            "total sold": 6
        }
    ],
    "Vegetables":[
        {
            "product":"Kale",
            "price":4.00,
            "cost":2.00,
            "total sold": 10
        },
        {
            "product":"Sunchokes",
            "price":3.20,
            "cost":1.00,
            "total sold": 5
         }
      ]
   }
}

以下是代码:


for(var key in foods.category) {
    foods.category[key].forEach(function(item, index) {
        // check if the id exists, if not write the category with id
        if(document.getElementById(key) === null){
             document.write("<h4" + " id='" + key + "'" + ">" + key + "</h4>")
        }
        document.write("<li>" + item.product + "</li>");
    });
}

结果如下:


肉类

  • NY Strip

  • 肉眼

蔬菜

  • 芥兰

  • Sunchokes

2 个答案:

答案 0 :(得分:0)

假设类别值是唯一的,以下内容应产生相同的结果。

for(var key in foods.category) {
      document.write("<h4" + " id='" + key + "'" + ">" + key + "</h4>")
      foods.category[key].forEach(function(item, index) {        
          document.write("<li>" + item.product + "</li>");
      });
}

答案 1 :(得分:0)

不确定您是否只是试图通过文档对象消除ID查询,但这只是通过正在构建的字符串进行查询。

var output = "";

for (var key in foods.category) {
    if (output.indexOf("<h4 id='" + key + "'") < 0) {
        output += "<h4" + " id='" + key + "'" + ">" + key + "</h4>";
    }
    foods.category[key].forEach(function (item, index) {
        // check if the id exists, if not write the category with id
        output += "<li>" + item.product + "</li>";
    });
}
document.querySelector('#output').innerHTML = output;

http://jsfiddle.net/phh7nsnv/1/