객체 배열 비교, 포함 여부 확인, filter 적용하기

Jayden ·2023년 10월 10일
0

1. === 연산 : 배열은 참조형이라서 === 연산을 사용하여 비교할 수 없다.

const artists = [{name : "이제훈", born : 1984},{name : "도경수", born : 1993},
                {name : "아이유", born : 1993}]

const IU = {name : "아이유", born : 1993}



console.log(artists[2])
console.log(IU)
console.log(artists[2] === IU)

/*
[object Object] {
  born: 1993,
  name: "아이유"
}
[object Object] {
  born: 1993,
  name: "아이유"
}

false
*/


위에 결과처럼 값이 동일한것 같지만, === 로 비교한 결과, false로 처리된다.

1. Object.entries().toString() 사용

const artists = [{name : "이제훈", born : 1984},{name : "도경수", born : 1993},
                {name : "아이유", born : 1993}]

const IU = {name : "아이유", born : 1993}




console.log(Object.entries(artists[2]))
console.log(Object.entries(IU))
console.log(Object.entries(artists[2]).toString() === Object.entries(IU).toString())

/*
  "name,아이유,born,1993"
  "name,아이유,born,1993"
   true
*/

2.JSON.stringify() 메서드 활용

비교할 값을 각각 " " 으로 감싼 스트링으로 변환하여 === 로 값이 같은지 판단한다.


const artists = [{name : "이제훈", born : 1984},{name : "도경수", born : 1993},
                {name : "아이유", born : 1993}]

const IU = {name : "아이유", born : 1993}




console.log(JSON.stringify(artists[2]))
console.log(JSON.stringify(IU))
console.log(JSON.stringify(artists[2]) === JSON.stringify(IU))

/*
  
  "{\"name\":\"아이유\",\"born\":1993}"
  "{\"name\":\"아이유\",\"born\":1993}"
  true

*/

2. 객체 포함 확인(string.prototype.includes() / JSON.stringify() 메소드 활용)

두 대상을 각각 string으로 변환하고 include() 메소드를 활용하여 포함여부를 확인할 수 있다.


const artists = [{name : "이제훈", born : 1984},{name : "도경수", born : 1993},
                {name : "아이유", born : 1993}]

const IU = {name : "아이유", born : 1993}



const artistsString = JSON.stringify(artists)

const IUString = JSON.stringify(IU)

console.log(artistsString)

console.log(IUString)

console.log(artistsString.includes(IUString))


"[{\"name\":\"이제훈\",\"born\":1984},{\"name\":\"도경수\",\"born\":1993},{\"name\":\"아이유\",\"born\":1993}]"

"{\"name\":\"아이유\",\"born\":1993}"

true

3. filter() 활용

개발을 진행하면서
useState나 recoil을 사용시 컴포넌트 상태값, 전역상태값을 설정시 객체 자체를 setState, setUseRecoilState의 파라미터로 적용해야 하는 경우가 있었다.
또한 해당 객체를 삭제할 경우 filter() 함수를 적용해야 했었다.

ex) 선수 리스트중에서 1999년생, 이름이 정우영인 객체를 제외한 리스트를 표시하고 싶다.

const athletes = [{name : "정우영", born : 1989, pos : "FW"},{name : "이승우", born : 1998, pos : "FW"}, {name : "정우영", born : 1999, pos : "MF"}]

const littleJung = {name : "정우영", born : 1999, pos : "MF"}

방법 1)

 const withoutLittleJung = athletes.filter((athlete)=>{
   if(athlete.name === littleJung.name && athlete.born === littleJung.born){
     return false
   }
   return true
 })

 console.log(withoutLittleJung)

방법 2)

 const withoutLittleJung = athletes.filter((athlete)=> (
     Object.entries(athlete).toString() !== Object.entries(littleJung).toString()
   )
 )

 console.log(withoutLittleJung)

방법 3)

const littleJungString = JSON.stringify(littleJung)
const withoutLittleJung =  athletes.filter((athlete) => (
      JSON.stringify(athlete) !== littleJungString))
   
console.log(withoutLittleJung)

콘솔 값

/*
[[object Object] {
  born: 1989,
  name: "정우영",
  pos: "FW"
}, [object Object] {
  born: 1998,
  name: "이승우",
  pos: "FW"
}]


*/

profile
프론트엔드 개발자

0개의 댓글