Hulk1991
Hulk1991

Reputation: 3163

AngularJS - Compare & Replace objects between 2 arrays

I have the following 2 arrays $scope.oldArray & $scope.newArray

$scope.oldArray = [{
    "status": "New",
    "priority_summary": "High",
    "u_id" : 1
}, {
    "status": "New",
    "priority_summary": "High",
    "u_id" : 2
}, {
    "status": "New",
    "priority_summary": "High",
    "u_id" : 3
}, {
    "status": "New",
    "priority_summary": "High",
    "u_id" : 4
}];

$scope.newArray = [{
    "status": "Old",
    "priority_summary": "Low",
    "u_id" : 1
}, {
    "status": "Old",
    "priority_summary": "High",
    "u_id" : 2
}, {
    "status": "New",
    "priority_summary": "Low",
    "u_id" : 3
}, {
    "status": "New",
    "priority_summary": "High",
    "u_id" : 4
}];

Here I need to compare these 2 arrays, then delete the changed object in $scope.oldArray & add the changed object from $scope.newArray to $scope.oldArray.

Note: Should not replace all the values from $scope.newArray to $scope.oldArray.

Upvotes: 0

Views: 121

Answers (1)

Yasemin çidem
Yasemin çidem

Reputation: 623

objects of arrays to compare can use angular.forEach

     angular.forEach(oldArray , function(value1, key1) {
            angular.forEach(newArray , function(value2, key2) {
                if (!(value1.status == value2.status&& 
                    value1.priority_summary==value2.priority_summary 
                    && value1.u_id==value2.u_id)) {
                    value1.status=value2.status;
                    value1.priority_summary=value2.priority_summary;
                    value1.u_id=value2.u_id;
                }
            });
    });

Upvotes: 1

Related Questions