«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
Recent Posts
Recent Comments
관리 메뉴

뉴히의 개발 로그

[TIL] 20230608 - 객체 합치기, 객체 내 같은 값 중복 제거 본문

개발일지/TIL

[TIL] 20230608 - 객체 합치기, 객체 내 같은 값 중복 제거

뉴히 2023. 6. 9. 00:10

팀프로젝트 막바지!

TMDB에서 데이터를 불러와서 사용하는데

인기순위, 최고평점등의 객체를 20개씩만 불러올 수 있었다.

그런데 더 불러와서 더보기로 보여주고 싶었기에

fetch를 두개 불러서 합쳐보기루

처음엔 각 다른 패치를 따로 불러오려했었는데

합펴서 같은 값을 제거한는게 더 쉬운듯 해서 객체 합치기 공부 :)

배열 메서드 concat() 

concat 은 메서드를 호출한 배열 뒤에 각 인수를 순서대로 붙여 새로운 배열을 만듭니다. 인수가 배열이면 그 구성요소가 순서대로 붙고, 배열이 아니면 인수 자체가 붙습니다. 중첩 배열 내부로 재귀하지 않습니다.

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
// Expected output: Array ["a", "b", "c", "d", "e", "f"]

예시코드

let arr1 = [
	{ id = "arrId1", date: "2023-06-08"},
    { id = "arrId2", date: "2021-06-08"}
];

let arr2 = [
	{ id = "arrId1", name = "jonh"},
    { id = "arrId3", name = "peter"}
]

일반 함수 사용시

let result = arr1.concat(arr2);


// 결과

0: { id = "arrId1", date: "2023-06-08"}
1: { id = "arrId2", date: "2021-06-08"}
2: { id = "arrId1", name = "jonh"}
3: { id = "arrId3", name = "peter"}

서로 다른 배열을 id를 기준으로 concat (Map 사용)

const map = new Map();
arr1.forEach(item => map.set(item.id, item));
arr2.forEach(item => map.set(item.id, {...map.get(item.id), ...item}));
const mergedArr = Array.from(map.values());

// 결과
0: { id = "arrId1", date: "2023-06-08", name = "jonh"}
1: { id = "arrId2", date: "2021-06-08"}
2: { id = "arrId3", name = "peter"}

같은 아이디의 데이터는 합쳐진당!

 

그리고 만약 같은 정보가 두번 중복되면!

합쳐져서 한개로 되도록? ㅎㅎ

//두개의 데이터 합침!
const newArray = movies.concat(moviesPopular);

const double = newArray.reduce(function (acc, current) {
    if (acc.findIndex(({ id }) => id === current.id) === -1) {
      acc.push(current);
    }
    return acc;
}, []);

이렇게하면 중복값빼고 새로운 배열을 받을 수 있당.

 

filter로도 가능!

newArray.filter((item, i) => {
  return (
    newArray.findIndex((item2, j) => {
      return item.id === item2.id;
    }) === i
  );
});


//3번째 인자 콜백함수 이용
newArray.filter(
  (arr, index, callback) => index === callback.findIndex(t => t.id === arr.id)
);

이렇게 다양하고 많은 방법이 있는데

왜 나는 한번에 떠오르지않는것인가...

 

참고 https://rosypark.tistory.com/530

참고 https://kyounghwan01.github.io/JS/JSbasic/dupulication-property-remove/#reduce