[TIL] JavaScript Object 비교

고은정·2021년 5월 24일
2

TIL

목록 보기
23/31
post-thumbnail

Object 비교

전역변수에 Object를 담아서, ajax 응답값의 Object와 비교하는 함수를 구현했습니다.

아래와 같이 currentObj와 newObj를 비교해서 Object가 일치하는 경우에는 true를, 다른 경우에는 해당 키를 리턴하도록 했습니다.

currentObj

{
  "name":"eunjeong",
  "age":26,
  "job":"student"
}

newObj

{
  "name":"eunjeong",
  "age":27,
  "job":"student"
}

사용하기

compareObject함수를 이용해서 리턴값을 얻습니다.

function compareObject(currentObj, newObj){
  if(JSON.stringify(currentObj) === JSON.stringify(newObj)){
    // 일치하는 경우 true return
    return true;
  }else{
    // 변경된 항목 return
    return Object.keys(currentObj).filter(function(key) {
      return currentObj[key] !== newObj[key];
    });
  }
}

예제에 적용하기

위에 정리한 내용을 간단하게 콘솔에서 실행하면 다음과 같습니다.

profile
개발이 하고싶어요

0개의 댓글