可以创建一个位置的数组吗?

时间:2018-06-21 14:44:03

标签: javascript html angularjs

我有问题。当JSON“客户”作为数组出现时,我的代码有效。 但是当只有1个客户时,我的代码将创建11个表列(JSON中的键数)。

JSON来自另一个应用程序,所以我无法更改

代码:

获得客户服务。

// Get the customers
promises.customers.$promise.then(function (data) {
    if (data['Customer']) {
        vm.customers = data['Customer'].customers;
        console.log(vm.customers);
    }
});

生成HTML。 就像我说的那样,如果它是一个数组,它会很好用,但是如果只有一个客户,它会创建11列,而不仅仅是一个。

 <thead>
   <tr>
     <th></th>
     <th ng-repeat="customer in vm.customers.Customers">Customer {{$index + 1}}</th>
   </tr>
 </thead>

此JSON有效:

{
  "Customers": [
   {
    "CUSTOMER_ID": "1",
    "FIRST_NAME": "Peter",
    "LAST_NAME": "Parker",
    "ACCOUNT_TYPE_DESCRIPTION": "Single Account",
    "BIRTH_DATE": "2018-06-21+00:00",
    "CUSTOMER_GENDER_DESCRIPTION": "Male",
    "STREET_ADDRESS": "Gotham Street 56",
    "POSTAL_CODE": "21312",
    "CITY": "Gotham",
    "COUNTRY_DESCRIPTION": "Portugal",
    "_xmlns": ""
  },
  "CUSTOMER_ID": "2",
    "FIRST_NAME": "Bla bla",
    "LAST_NAME": "Parker",
    "ACCOUNT_TYPE_DESCRIPTION": "Single Account",
    "BIRTH_DATE": "2018-06-21+00:00",
    "CUSTOMER_GENDER_DESCRIPTION": "Male",
    "STREET_ADDRESS": "Gotham Street 56",
    "POSTAL_CODE": "21312",
    "CITY": "Gotham",
    "COUNTRY_DESCRIPTION": "Portugal",
    "_xmlns": ""
  }
  ],
  "_xmlns": "http://www.infinity.com/bpm/model/CMT/Customers"
}

这不是

    {
  "Customers": {
    "CUSTOMER_ID": "1",
    "FIRST_NAME": "Peter",
    "LAST_NAME": "Parker",
    "ACCOUNT_TYPE_DESCRIPTION": "Single Account",
    "BIRTH_DATE": "2018-06-21+00:00",
    "CUSTOMER_GENDER_DESCRIPTION": "Male",
    "STREET_ADDRESS": "Gotham Street 56",
    "POSTAL_CODE": "21312",
    "CITY": "Gotham",
    "COUNTRY_DESCRIPTION": "Portugal",
    "_xmlns": ""
  },
  "_xmlns": "http://www.infinity.com/bpm/model/CMT/Customers"
}

2 个答案:

答案 0 :(得分:1)

您可以检查它是否为数组,如果不是,则创建一个数组。

promises.customers.$promise.then(function (data) {
    if (data['Customer']) {
        vm.customers = data['Customer'].customers;

        // if not an array then assume that vm.customers is actually a single
        // instance in which case create a new array 
        // with that as the 1st element
        if(!Array.isArray(vm.customers)){
            vm.customers = [vm.customers];
        }

        console.log(vm.customers);
    }
});

答案 1 :(得分:0)

尝试

promises.customers.$promise.then(function (data) {
    if (data['Customer']) {
        if( Array.isArray( data['Customer'].customers ) ) { 
            vm.customers = data['Customer'].customers;
            console.log(vm.customers);
        }else{
            vm.customers = [data['Customer'].customers];
            console.log(vm.customers);
        }
    }
});