Loop through json array in jQuery list

I have this JSON array

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

I want him to look through my list, but I have no idea how to do it all that I can do so far lists one item at a time. In addition, I can only list the product, not the product = price. The jQuery inst forum helps ... thanks!

Here is the rest of the code

function loadList() {
//  var list = document.getElementById('productList');
    var list = $("#productList").listview();

    var listItem = document.createElement('li');
    listItem.setAttribute('id', 'listitem');

    listItem.innerHTML = productList.products[0].description;

    $(list).append(listItem);
    $(list).listview("refresh");

and html file

<html xmlns:f="http://www.lipso.com/f" xmlns:l="http://www.lipso.com/v2/lml" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<head>
    <title>Page Title</title>
    &meta;
    <script src="@=site.cfg.resources.url@/test.js"></script>
</head>
<body onLoad="loadList()">
<div data-role="page">
    <div data-role="header" id="header">
        <h1>Dynamic Product List</h1>
    </div>
    <div data-role="content" id="content">
        <ul id="productList" data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b">
        </ul>
    </div>
</div>
</body>
</html>
+5
source share
4 answers

Since you are already using jQuery, why not use the $ function . each () ?

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>');
});
+13
source

Check out jQuery.each ()

$.each(productList.products, function(index, value) {
   $(list).append('<li>' + value.description + ': ' + value.price + '</li>');
});
+3
source

"JSON-" JavaScript, , , . productlist - , , , 2 ( ). , , 0 - 1.... " ()".

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

Javascript Object.

for (var i = 0; i < productList.products.length; i ++) {
  for (var key in productList.products) {
    alert(key + ":" + productList.products[key]);
  }
}
0
0

All Articles