2016-10-26 2 views
0

객체 배열을 반복하고 새로운 객체 (고유 한 이름이있는 객체)를 푸시하고 이미 본 객체를 업데이트하는 함수를 작성하려고합니다.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 문이 잘못되었을 수도 있다고 생각합니다.

또한 작은 데이터 세트를 사용하는 단순한 예이기 때문에 각 이름에 대해 배열을 하드 코딩해도 작동하지 않습니다.

누구든지 빌려 줄 수 있습니까?

+1

나는 단순히 그런 일을 내가 사용하면됩니다 무엇 angular forEach 그리고 당신의 경우에는 세 가지 배열을 만들어이 정보로 채 웁니다. 그런 다음 indexof를 사용하여 myNewArray로 푸시합니다. 배열 객체보다 간단한 배열 작업이 더 쉽습니다. – ThatBird

+0

@ThatBird는 내가 그것을 할 수 있으면 좋겠다. 불행히도, 이것은 내가 성취하고자하는 것의 단순한 버전이다. 따라서이 예제에서는 세 개의 배열이 작동하지만 더 큰 데이터 세트를 사용하면 배열이 작동하지 않습니다. 또한 제안 된 접근 방법을 사용하면 동적 인 작업이되지 않습니다. 하지만 오히려 하드 코드 된 – NoReceipt4Panda

+0

글쎄, 나는이 방법으로 약 50,000 값 (대부분이 이상)에서 일한 적이 있고 어떤 문제도 겪지 않았다. 그래도 데이터 객체 (귀하의 경우에는 myArray)에 수신 할 내용을 사전에 알고 있어야합니다. – ThatBird

답변

2

이 방법을 시도해보십시오

  1. 이름 재산 및 이전에 생성 된 개체의 키 이상 적용 이미 계산 (Array.prototype.reduce)
  2. 으로 반복과 함께 있는 객체를 생성 및 변환 다시 배열로 (Object.keysArray.prototype.map)
적은 하드 용액을 첨가3210

var res = {}; 
 
res = Object.keys([ 
 
    { "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 }, 
 
].reduce(function (res, item) { 
 
    if (res[item.name]) { 
 
    res[item.name].total += item.total; 
 
    res[item.name].applicable += item.applicable; 
 
    } 
 
    else { 
 
    res[item.name] = item; 
 
    } 
 
    return res; 
 
}, res)).map(function(key) { 
 
    return res[key]; 
 
}); 
 
console.log(res);

는 :

var 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 }, 
 
]; 
 

 
var res = {}; 
 
    
 
// add keys for loopable integers which will be summed 
 
var loopables = Object.keys(myArray[0]).filter(function (key) { 
 
    return Number.isInteger(myArray[0][key]); 
 
}); 
 

 
res = Object.keys(myArray.reduce(function (res, item) { 
 
    if (res[item.name]) { 
 
    loopables.forEach(function (loopableKey) { 
 
     res[item.name][loopableKey] += item[loopableKey]; 
 
    }); 
 
    
 
    } 
 
    else { 
 
    res[item.name] = item; 
 
    } 
 
    return res; 
 
}, res)).map(function(key) { 
 
    return res[key]; 
 
}); 
 
console.log(res);
여기

난 단지 주요 키 이름에 의존하고, 나머지 정수 속성이 자동으로 합산되어 반복 가능 루프 가능 키 배열, calc 각도와 처음

plunker에서 ulated : https://plnkr.co/edit/MRr2QRULG8TYs2CqA1By?p=preview

+0

이것은 좋지 않지만 개체 배열이 명시 적으로 지정되지 않은 경우 위의 코드가 어떻게 작동하는지 설명 할 수 있습니까? 배열을 하드 코딩하지 않고 이미 변수로 설정 했습니까? 예를 들어'$ scope.myArray'라고합니다. 배열 선언 중간에'reduce' 함수가 있기 때문에 물어 봅니다. – NoReceipt4Panda

+1

내 대답을 다른 스 니펫으로 업데이트했습니다. 여기서 배열은 변수에 있고 합계 값은 프로그래밍 방식으로 계산됩니다. – Andriy

1

내가 각도 대해 forEach를 사용하고 경우에, 나는 세 가지 배열을 만들어 주겠다고하고이 정보를 채워입니다 단순히 같은 일을 무엇. 그런 다음 indexof를 사용하여 myNewArray로 푸시합니다. 배열 객체보다 간단한 배열 작업이 더 쉽습니다.

예를 들면 forEach Angular forEach.

1

난 당신이

점검이 다음 코드는

var obj = [{ 
 
      "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 
 
}, ]; 
 

 
     var newObj = []; 
 

 
     MergeObjectProperties(obj); 
 

 
     function MergeObjectProperties(obj) { 
 
      Object.keys(obj).forEach(function (key) { 
 
       var name = obj[key].name; 
 
       var exists = checkProperty(name, newObj) 
 
       if (newObj.length == 0 || !exists) 
 
        newObj.push(obj[key]); 
 
       else { 
 
        newObj[exists]["total"] = obj[key].total + newObj[exists]["total"]; 
 
        newObj[exists]["applicable"] = obj[key].applicable + newObj[exists]["applicable"]; 
 
       } 
 
      }); 
 
     console.log(newObj); 
 
     } 
 

 
     function checkProperty(prop, newObj) { 
 
      var result; 
 
      Object.keys(newObj).forEach(function (key) { 
 
       if (newObj[key]["name"] === prop) { 
 
        result = key 
 
       } 
 
      }); 
 
      return result; 
 
     }

희망이 도움이 순수 자바 스크립트에서 그것을 할 수 있다고 생각