gpt4 book ai didi

javascript - 你能创建一个只有一个位置的数组吗?

转载 作者:行者123 更新时间:2023-11-30 20:25:36 25 4
gpt4 key购买 nike

我有一个问题。当 JSON“Customers”作为数组出现时,我的代码有效。 但是当它只有 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"
}

最佳答案

你可以检查它是否是一个数组,如果不是就创建一个。

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);
}
});

关于javascript - 你能创建一个只有一个位置的数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50971358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com