gpt4 book ai didi

javascript - 大写与小写

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

我有一个简单的问题。

我有多种方法可以从我无法控制的其他应用程序获取 JSON。所有键都具有相同的名称,但有些是大写的,有些是小写的。

我如何读取 JSON 以便不管它是小写还是大写?

例如在我的代码中,当 json 的 customer_id 为小写时,它不起作用

HTML

 <td ng-repeat="customer in customers">{{customer.CUSTOMER_ID}}</td> // this only works when the JSON keys comes uppercase

Controller

// Get Customers
promises.customers.$promise.then(function (data) {
$scope.customers = data["Customers"].Customers;

if(!angular.isArray($scope.customers)) {
$scope.customers = [$scope.customers];
}
console.log($scope.customers);
}.bind(this));

最佳答案

您可以将属性规范化为全部大写或小写:

// Customers with a sample customer as provided in some comment by the OP
const customers = [{
"account_id": 1,
"account_type_description": "Single Account",
"customer_id": 1,
"first_name": "Peter",
"last_name": "Parker",
"identity_card_number": 128,
"tax_identification": 35,
"birth_date": "2018-06-28T07:57:23Z",
"customer_gender_description": "Male",
"street_address": "Gotham Street 56",
"postal_code": "21312",
"city": "Gotham",
"country_description": "Portugal"
},
{
"ACCOUNT_ID": 1,
"ACCOUNT_TYPE_DESCRIPTION": "Single Account",
"CUSTOMER_ID": 1,
"FIRST_NAME": "Peter",
"LAST_NAME": "Parker",
"IDENTITY_CARD_NUMBER": 128,
"TAX_IDENTIFICATION": 35,
"BIRTH_DATE": "2018-06-28T07:57:23Z",
"CUSTOMER_GENDER_DESCRIPTION": "Male",
"STREET_ADDRESS": "Gotham Street 56",
"POSTAL_CODE": "21312",
"CITY": "Gotham",
"COUNTRY_DESCRIPTION": "Portugal"
}
]

const normalizeProperties = entities => entities.map(customer => {
const outputCustomer = {}

for (let property of Object.keys(customer))
outputCustomer[property.toLowerCase()] = customer[property]

return outputCustomer
})

const normalizedCustomers = normalizeProperties(customers)

console.log(JSON.stringify(normalizedCustomers))

有很多方法可以获得相同的结果,但我们的想法是,一旦将模型绑定(bind)到 UI,您就不希望出现这些差异。

关于javascript - 大写与小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51081010/

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