프로젝트를 진행하다가 보니..
서로 다른 JSON Object의 키와 값이 동일하게 들어있는지 비교해야할때가 있다.
예를 들어, 아래와 같은 JSON Object가 두개 있을때, 서로 동일하다는 리턴값을 받으려면 어떻게 해야할까?
var obj = { id: 1, name: "myName" };
var obj2 = { name: "myName", id: 1 };
obj == obj2 // false 리턴.
obj === obj2 // false 리턴.
만약, AngularJS를 사용한다면, 아래와 같이 간단하게 비교할 수 있다.
var obj = { id: 1, name: "myName" };
var obj2 = { name: "myName", id: 1 };
angular.equals(obj, obj2) // true 리턴.
여러방면으로 찾아봤지만, jQuery 내장 함수나, JavaScript 의 Prototype 함수를 통해서는..
내가 원하는 기능을 구현 할 수 없는 것 같다.
아래의 함수를 프로젝트에 추가한다.
Object.equals = function(x, y) {
if (x === y) return true;
// if both x and y are null or undefined and exactly the same
if (!(x instanceof Object) || !(y instanceof Object)) return false;
// if they are not strictly equal, they both need to be Objects
if (x.constructor !== y.constructor) return false;
// they must have the exact same prototype chain, the closest we can do is
// test there constructor.
for (var p in x) {
if (!x.hasOwnProperty(p)) continue;
// other properties were tested using x.constructor === y.constructor
if (!y.hasOwnProperty(p)) return false;
// allows to compare x[ p ] and y[ p ] when set to undefined
if (x[p] === y[p]) continue;
// if they have the same strict value or identity then they are equal
if (typeof(x[p]) !== "object") return false;
// Numbers, Strings, Functions, Booleans must be strictly equal
if (!Object.equals(x[p], y[p])) return false;
// Objects and Arrays must be tested recursively
}
for (p in y) {
if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) return false;
// allows x[ p ] to be set to undefined
}
return true;
}
그럼, 아래와 같이 사용할 수 있다.
var obj = { id: 1, name: "myName" };
var obj2 = { name: "myName", id: 1 };
Object.equals(obj, obj2) // true 리턴.
'JavaScript > JavaScript' 카테고리의 다른 글
fancy tree에서 커스텀 아이콘 추가하기. (0) | 2018.05.11 |
---|