[JavaScript] 객체의 값 비교하기

Dam·2023년 9월 23일
post-thumbnail

객체의 값 비교

object(객체)는 참조형이기 때문에 key, value 값 및 순서가 같은 object를 === 으로 비교할 수가 없다. 따라서 참조형을 원시형으로 바꾸어서 비교해주어야 한다.
단, 순서가 보장된 객체의 비교만 가능하고 순서가 보장되어 있지 않은 경우, 다음과 같이 sort와 reduce를 사용해 순서를 보장해준 뒤 객체를 비교할 수 있다.

const one = {
	fruit: '🍉',
 	nutrients: {
    	energy: '255kJ',
      	minerals: {
        	name: 'calcium'
        }
    }
};

const two = {
	fruit: '🍉',
 	nutrients: {
    	energy: '255kJ',
      	minerals: {
        	name: 'calcium'
        }
    }
};

key 순서가 정해진 객체의 비교

1. JSON.stringify 사용

// Using JSON
JSON.stringify(one) === JSON.stringify(two);  // true
  • JSON.stringify(a) : a에 들어가는 객체, 배열, string 등 모든 값을 string으로 묶어주는 역할을 한다.
{"fruit":"🍉","nutrients":{"energy":"255kJ","minerals":{"name":"calcium"}}}

2. Object.entries 사용

// Using Object.entries
Object.entries(one).toString() === Object.entries(two).toString();  // true
  • Object.entries(one)는 array를 리턴하는데, 이중 배열로서 key, value 값을 각각 담고 있는 배열을 리턴한다.
[
  [ 'fruit', '🍉' ],
  [ 'nutrients', { energy: '255kJ', minerals: [Object] } ]
]
  • 이제 비교할 수 있도록 return 값을 toString()으로 변환해주면, string으로 return 하기 때문에 비교가 가능하다.
fruit,🍉,nutrients,[object Object]

key 순서가 정해지지 않은 객체의 비교

만약 객체의 key 순서가 보장되어 있지 않을 경우, 다른 방식으로 객체의 값을 비교해야 한다.
예를 들어 서버의 데이터베이스의 값들을 객체화 할 때
{splitter : true, plate : true} 로 들어올 때도 있고, {plate : true, splitter : true} 로 들어오기도 해서 제대로 된 비교를 하려면 다음과 같은 하드 코드를 작성해야 한다.

// 1. 객체의 key 값을 sort()를 통해 정렬해준다.
// 2. 정렬된 key를 reduce로 순회하면서 key value를 첫 {} 안에 순서대로 입력해준다.
let one_sort = Object.keys(one).sort().reduce((obj, key) => (obj[key] = one[key], obj), {});
let two_sort = Object.keys(two).sort().reduce((obj, key) => (obj[key] = two[key], obj), {});

console.log(one_sort);	// { "plate": true, "splitter": true }
console.log(two_sort);	// { "plate": true, "splitter": true }

console.log(JSON.stringify(one_sort) === JSON.stringify(two_sort));
// true
console.log(Object.entries(one_sort).toString() === Object.entries(two_sort).toString());
// true
profile
⏰ Good things take time

0개의 댓글