Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular equals with deep comparison and return difference on each item

I want to compare two arrays using angular.equals and get list of items that are different from each other.

For example:

var obj1 = [
    { id: 1, name: 'john', age: 30, height: 6 },
    { id: 2, name: 'ben' , age: 20, height: 5 }
];
var obj2 = [
    { id: 1, name: 'martin', age: 25, height: 6 },
    { id: 2, name: 'ben'   , age: 20, height: 5 }
];

Now doing angular.equals(obj1, obj2) will return false.

Here I want to compare each item from different arrays and alert differences or show different color when I display in UI.

Assuming obj1 is from HTML form and obj2 is from service.

Result expected:

.id[1] name changed to john,age changed to 25
or
.get false or true when I compare each item in.

like image 860
user2927423 Avatar asked May 29 '14 06:05

user2927423


1 Answers

Angular doesn't have a built-in function for this. You should use the library deep-diff for this.

var first = [
    { id: 1, name: 'john', age: 30, height: 6 },
    { id: 2, name: 'ben' , age: 20, height: 5 }
];

var second = [
    { id: 1, name: 'martin', age: 25, height: 6 },
    { id: 2, name: 'ben'   , age: 20, height: 5 }
];

var result = diff(first, second);

// result => [
//    { kind: 'E', path: [0, 'name'], lhs: 'john', rhs: 'martin' },
//    { kind: 'E', path: [0, 'age' ], lhs: 30    , rhs: 25       }
// ]
like image 151
Phú Avatar answered Jan 03 '23 22:01

Phú