1

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?

2
  • you don't need another for loop. since it looks there is only 1 subproduct by your usage subproducts[0] you need to check fot its existence/length Commented Jan 24, 2014 at 22:11
  • there is potentially more than one subproduct, but I only need to select one out of those Commented Jan 24, 2014 at 22:21

1 Answer 1

1

Just check if the array contains anything with length before you try to access it :

$.getJSON('url' + name, function(data) {
    $.each( data.response.products, function(i, product) {
        var tr  = $('<tr />'),
            sub = product.subproducts.length ? product.subproducts[0].subproductname : '',
            td1 = $('<td />', {
                 'class' : 'name', 
                 text    : product.name
            }),
            td2 = $('<td />', {
                 'class' : 'id', 
                 text    : product.productid
            }),
            td3 = $('<td />', {
                 'class' : 'subproductid', 
                 text    : sub
            });

        tr.append(td1, td2, td3).appendTo('#table');
    });
});

if you need to, you can be more thorough, checking every step of the way.

var sub = '';

if ('subproducts' in product) { // that key exists

    if ( Array.isArray(procuct.subproducts) ) { // it's an array

        if ( procuct.subproducts.length ) { // it's not empty

            if ( 'subproductname' in procuct.subproducts[0] ) // and that key exists

                 sub = product.subproducts[0].subproductname;

            }
        }
    }
}

This is really verbose, and not the way you'd normally write something like this as you can join the checks in one single if statement, and you shouldn't really have to check every single thing, but you have to decide how uncertain you are that keys and objects will exist, and test for the things that could be missing etc. The above only shows you the different tests you can do.

Sign up to request clarification or add additional context in comments.

1 Comment

This is really great. Used the first method and it's a neat way of structuring the complex JSON data i'm retrieving. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.