I'm retrieving JSON by the Get method in jQuery and appending the data to an HTML table.
The JSON data is structured like this:
{
"response":{
"message":"correct"
},
"products":[
{
"name":"tools",
"productid":"14",
"subproducts":[
{
"subproductname":"hammer",
"subproductid":"24"
},
{
"subproductname":"screw",
"subproductid":"28"
},
],
},
{
"name":"utilities",
"productid":"15",
"subproducts":[],
},
]
}
}
I can successfully parse the JSON to retrieve each instance of name and productid from the data and append to a new row in the table. However, i'm having trouble retrieving the subproductname from the data as the subproducts array does not always contain data (see above for a simple example).
My jQuery code looks like this:
$.getJSON('url' + name, function(data) {
for (var i = 0; i < data.response.products.length; ++i) {
var tr = $('<tr/>');
tr.append("<td class='name'>" + data.response.products[i].name + "</td>");
tr.append("<td class='id'>" + data.response.products[i].productid + "</td>");
tr.append("<td class='subproductid'>" + data.response.products[i].subproducts[0].subproductname + "</td>");
$('#table').append(tr);
};
});
As it stands, I've added [0] to subproducts in the tr.append line which works to a small extent but my problem is that the data is only appended where the subproducts array also contains data. I'd like to be able to append all data where the product array is present regardless of whether the subproducts array contains any data. If there is data in the subproducts array it will be added into its td class but if not the text in the td class should remain blank and the name and productid data should still be appended.
I'm stumped as to how I'd overcome this - my thinking is I need to add another for line before I append the data to the table. Am I on the right lines here?
subproducts[0]you need to check fot its existence/lengthsubproduct, but I only need to select one out of those