大写与小写 [英] Uppercase vs Lowercase

查看:40
本文介绍了大写与小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题.

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

I have multiple ways to get a JSON from other apps that i dont control. All the keys have the same name but some are uppercase and some are lowercase.

我如何读取JSON,所以无论大小写都无关紧要?

How do I read the JSON so it doesn't matter if it's lowercase or uppercase?

例如在我的代码中,当json的小写字母 customer_id 无效

For example in my code when the json has customer_id in lowercase it does not work

HTML

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

控制器

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

推荐答案

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

You may normalize properties to be all in uppercase or lowercase:

// 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))

有很多方法可以得到相同的结果,但是我们的想法是,一旦将模型绑定到UI上,您就不需要这些差异.

There're many approaches to get the same result, but the idea is that you don't want those differences once you bind the model to the UI.

这篇关于大写与小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆