所以我有一个角度函数,旨在从一个对象数组中获取一些基本细节,通过查找使用id传递给函数。
无论如何,这个功能是第一次运作。也就是说,它成功返回合同ID匹配的第一个对象的客户名称。但是,如果有多个匹配的合同/对象,则只返回第一个名称。
我知道这一定是循环方面的一个基本问题,但似乎无法让它工作!
非常感谢。
这是功能:
$scope.getCompanyDetailsByContractId = function(contractId) {
for (var i = $scope.customers.length - 1; i >= 0; i--) {
if ($scope.customers[i].contracts[i].id == contractId ) {
return $scope.customers[i].name;
};
};;
}
以下是数据结构:
$scope.customers = [{
id: 1,
name: "John Inc",
currentContractLength: 12,
currentContractValue: 18000,
startDate: "09/01/2014",
endDate: "09/01/2015",
nextRenewalDate: "09/01/2015",
mrr: 1500,
contracts: [{
id: 234,
status: "won",
contractNumber: 1,
value: 18000,
startDate: "09/01/2014",
endDate: "09/01/2015",
nextRenewalDate: "09/01/2014"
},
{
id: 235,
status: "pending",
contractNumber: 2,
value: 18000,
startDate: "09/01/2015",
endDate: "09/01/2016",
nextRenewalDate: "09/01/2016"
}]
}, {
id: 2,
name: "Peters Company Ltd",
currentContractLength: 3,
currentContractValue: 15000,
startDate: "09/01/2014",
endDate: "09/01/2015",
nextRenewalDate: "09/01/2015",
mrr: 1500,
contracts: [{
id: 543654,
status: "won",
contractNumber: 1,
value: 4200,
startDate: "09/01/2014",
endDate: "09/01/2015",
nextRenewalDate: "09/01/2014"
},
{
id: 54354,
status: "pending",
contractNumber: 2,
value: 18000,
startDate: "09/01/2015",
endDate: "09/01/2016",
nextRenewalDate: "09/01/2016"
}]
}];
答案 0 :(得分:1)
看起来你应该做2个循环来查看所有可能的合同。
通过以下调用,您只查找索引为i
$scope.customers[i].contracts[i].id == contractId
也许你应该做像
这样的事情for (var i = $scope.customers.length - 1; i >= 0; i--) {
for (var j = 0; j < $scope.customers[i].contracts.length; j++) {
if ($scope.customers[i].contracts[j].id == contractId ) {
return $scope.customers[i].name;
};
}
};