I am getting some Json from the server that I loop through to dynamically build a table in the dom.
When there are more than one objects the data is returned as an array of objects
like this:
{
"ProductList": {
"Products": [{
"ProductID": "1",
"Name": "ProdName"},
{
"ProductID": "2",
"Name": "ProdName2"}]
}
}
however when there is only one object it is returned simply as an object and not an array like this:
{
"ProductList": {
"Products": {
"ProductID": "3",
"Name": "ProdName3"
}
}
}
So what I have been doing is checking if it is an array like this:
if ($.isArray(productDetails.ProductList.Products) === true) {
for (i = 0; i < productDetails.ProductList.Products.length; i++) {
//Create the dom elements by accessing the object properties with [i]
//ie. productDetails.ProductList.Products[i].ProductsID
}
}
else {
//Create the dom elements by accessing the object properties w/o [i]
//ie. productDetails.ProductList.Products.ProductsID
}
It works but I have a lot of code that is exactly the same except for the way the object properties are accessed and whenever I change one i need to remember to change the other or I will have problems.
On the client side is their a better way to handle this?
How about converting
productsto array if it’s not?