객체 배열을 반복하고 새로운 객체 (고유 한 이름이있는 객체)를 푸시하고 이미 본 객체를 업데이트하는 함수를 작성하려고합니다.AngularJS : 개체의 배열에 값이 있는지 확인하는 방법?
예를 들어, 내가이 배열이 말 : 함수의 말까지
$scope.myArray = [
{ "name": "Apple", "total": 16, "applicable": 21 },
{ "name": "Cherry", "total": 12, "applicable": 27 },
{ "name": "Plum", "total": 14, "applicable": 21 },
{ "name": "Apple", "total": 16, "applicable": 21 },
{ "name": "Cherry", "total": 12, "applicable": 27 },
{ "name": "Plum", "total": 14, "applicable": 21 },
{ "name": "Banana", "total": 14, "applicable": 21 },
];
를 새로운 배열은 다음과 같아야합니다
여기$scope.myNewArray = [
{ "name": "Apple", "total": 32, "applicable": 42},
{ "name": "Cherry", "total": 24, "applicable": 54},
{ "name": "Plum", "total": 28, "applicable": 42},
{ "name": "Banana", "total": 14, "applicable": 21 },
];
내가 지금까지이 내용은 다음과 같습니다
$scope.myArray = [
{ "name": "Apple", "total": 16, "applicable": 21 },
{ "name": "Cherry", "total": 12, "applicable": 27 },
{ "name": "Plum", "total": 14, "applicable": 21 },
{ "name": "Apple", "total": 16, "applicable": 21 },
{ "name": "Cherry", "total": 12, "applicable": 27 },
{ "name": "Plum", "total": 14, "applicable": 21 },
{ "name": "Banana", "total": 14, "applicable": 21 },
];
$scope.myNewArray = [];
$scope.myArray.filter(function() {
var i = $scope.myNewArray.indexOf($scope.myArray.name);
if ($scope.myNewArray.indexOf($scope.myArray.name) < 0)
$scope.myNewArray.push($scope.myArray);
else {
$scope.myNewArray[i].total += $scope.myArray.total;
$scope.myNewArray[i].applicable += $scope.myArray.applicable;
}
});
내가 만나는 문제는 모든 것이 t 그는 새로운 배열. 그것과 나는 이전 레코드에 값을 추가하는 다른 else 문이 잘못되었을 수도 있다고 생각합니다.
또한 작은 데이터 세트를 사용하는 단순한 예이기 때문에 각 이름에 대해 배열을 하드 코딩해도 작동하지 않습니다.
누구든지 빌려 줄 수 있습니까?
나는 단순히 그런 일을 내가 사용하면됩니다 무엇 angular forEach 그리고 당신의 경우에는 세 가지 배열을 만들어이 정보로 채 웁니다. 그런 다음 indexof를 사용하여 myNewArray로 푸시합니다. 배열 객체보다 간단한 배열 작업이 더 쉽습니다. – ThatBird
@ThatBird는 내가 그것을 할 수 있으면 좋겠다. 불행히도, 이것은 내가 성취하고자하는 것의 단순한 버전이다. 따라서이 예제에서는 세 개의 배열이 작동하지만 더 큰 데이터 세트를 사용하면 배열이 작동하지 않습니다. 또한 제안 된 접근 방법을 사용하면 동적 인 작업이되지 않습니다. 하지만 오히려 하드 코드 된 – NoReceipt4Panda
글쎄, 나는이 방법으로 약 50,000 값 (대부분이 이상)에서 일한 적이 있고 어떤 문제도 겪지 않았다. 그래도 데이터 객체 (귀하의 경우에는 myArray)에 수신 할 내용을 사전에 알고 있어야합니다. – ThatBird