如何处理有时在对象数组中返回的Json数据,有时只返回对象?

eto*_*bot 2 javascript jquery

我从服务器中获取了一些Json,我在dom中动态构建一个表.当有多个对象时,数据将作为对象数组返回,如下所示:

{
    "ProductList": {
        "Products": [{
            "ProductID": "1",
            "Name": "ProdName"},
        {
            "ProductID": "2",
            "Name": "ProdName2"}]
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当只有一个对象时,它只是作为一个对象而不是像这样的数组返回:

{
    "ProductList": {
        "Products": {
            "ProductID": "3",
            "Name": "ProdName3"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我一直在做的是检查它是否是这样的数组:

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
}
Run Code Online (Sandbox Code Playgroud)

它工作但我有很多代码完全相同,除了访问对象属性的方式,每当我改变一个我需要记住改变另一个或我将有问题.客户端是他们处理这个问题的更好方法吗?

Nik*_*bak 8

products如果不是那么转换为数组怎么样?

var products = productDetails.ProductList.Products;
if (!$.isArray(products)) {
    products = new Array(products);
}

... all logic here
Run Code Online (Sandbox Code Playgroud)