我有一个要遍历的对象数组。使用一个函数,我想给出对象的“类型”并为其获取“值”。
例如:
数组:
$scope.data = [
{
"type": "CUSTOMER_NO",
"value": "12345"
},
{
"type": "NAME_LINE_1",
"value": "CURTIS"
},
{
"type": "ADDR_STREET1",
"value": "500 RODEO DR"
},
{
"type": "ADDR_STREET2",
"value": "SUITE 102, MD 0750"
},
{
"type": "ADDR_CITY",
"value": "SAINT JOSEPH"
},
{
"type": "ADDR_ZIP",
"value": "22331"
}
]
controller(forloop):
$scope.formatAddress = function(addressInfo) {
angular.forEach($scope.data, function(addressValue) {
switch(addressValue.type) {
case "CUSTOMER_NO":
address = addressValue.value;
break;
case "ADDR_STREET1":
address = addressValue.value;
break;
case "ADDR_STREET2":
address = addressValue.value;
break;
case "NAME_LINE_1":
address = addressValue.value;
break;
case "NAME_LINE_2":
address = addressValue.value;
break;
case "ADDR_CITY":
address = addressValue.value;
break;
case "ADDR_ZIP":
address = addressValue.value;
break;
default:
address = addressValue.value;
}
});
return address;
};
我正在使用forEach和使用switch遍历数组,以检查将哪个字符串传递给我想要的特定类型。
在HTML中:
<div>{{vm.formatAddress("CUSTOMER_NO")}} - {{vm.formatAddress("NAME_LINE_1")}}</div>
<div>{{vm.formatAddress("ADDR_STREET1")}} {{vm.formatAddress("ADDR_STREET2")}}</div>
<div>{{vm.formatAddress("ADDR_CITY")}}, {{vm.formatAddress("CUSTOMER_NO")}} - {{vm.formatAddress("ADDR_ZIP")}}</div>
我现在要回去的是...。就像这样的客户号码...
12345 - 12345
12345 12345
12345, 12345 - 12345
我想找回什么...
12345 - CURTIS
500 RODEO DR, SAINT JOSEPH
SUITE 102, MD 0750
SAINT JOSEPH, 22331
编辑:
使用for循环解决了该问题
答案 0 :(得分:3)
如果我正确理解了您的问题,则可以将$ scope.formatAddress替换为:
$scope.formatAddress = function(addressInfo) {
return data.find(x => x.type === addressInfo).value;
};