looping through JSON array in a jQuery list

前端 未结 4 1329
长情又很酷
长情又很酷 2021-01-12 19:10

I have this JSON array

// Json array
var productList = {\"products\": [
    {\"description\": \"product 1\", \"price\": \"9.99\"},
    {\"description\": \"pr         


        
相关标签:
4条回答
  • 2021-01-12 19:39

    Since you're already using jQuery, why don't you use the $.each() function?

    Instead of this code:

    var listItem = document.createElement('li');
    listItem.setAttribute('id', 'listitem');
    
    listItem.innerHTML = productList.products[0].description;
    
    $(list).append(listItem);
    

    Use this:

    $(productList.products).each(function(index){
        $(list).append('<li id="listitem">' + this.description + " = " + this.price + '</li>');
    });
    
    0 讨论(0)
  • 2021-01-12 19:39

    Check out jQuery.each()

    $.each(productList.products, function(index, value) {
       $(list).append('<li>' + value.description + ': ' + value.price + '</li>');
    });
    
    0 讨论(0)
  • 2021-01-12 19:43

    Using the "JSON array" or better named JavaScript object described below you can loop through it using for loops. productlist is an object that contains an array and each element in this array is an object that contains 2 properties or variables (description and price). The array can be iterated though using a typical for loop starting at 0 and ending at the array lenght - 1....the objects inside each array element can be iterated through using the "for (key in object)" notation.

    // Json array
    var productList = {"products": [
        {"description": "product 1", "price": "9.99"},
        {"description": "product 2", "price": "9.99"},
        {"description": "product 3", "price": "9.99"}
    ]
    };
    

    Here is an example of iterating through your Javascript Object.

    for (var i = 0; i < productList.products.length; i ++) {
      for (var key in productList.products) {
        alert(key + ":" + productList.products[key]);
      }
    }
    
    0 讨论(0)
  • 2021-01-12 19:47

    I appears to me that what you really need is the .tmpl plugin to build your list from your json data:

    http://api.jquery.com/jquery.tmpl/

    0 讨论(0)
提交回复
热议问题