
게시물 dataA 가 있고, 게시물의 작성자 dataB 가 있다.
데이터 A, B 를 합쳐서 front 에 보여주려고 함.
// 게시물 데이터
const dataA = [
{
id: 1,
title: "sunt aut facere repellat provident occaecati",
body: "quia et suscipit nsuscipit",
author: "고길동",
userUuid: "aaa123",
},
{
id: 2,
title: "qui est esse",
body: "est rerum tempore vitae nsequi sint nihil reprehenderit dolor beatae",
author: "둘리",
userUuid: "bbb123",
},
{
id: 3,
title: "ea molestias quasi exercitationem repellat qui ipsa",
body: "et iusto sed quo iure nvoluptatem occaecati omnis eligendi aut",
author: "마이콜",
userUuid: "ccc123",
},
];
여기서 dataB 와 매칭 할 값은 author 와 userUuid 이다.
// 유저 데이터
const dataB = [
{
userUuid: "aaa123",
name: "고길동",
age: 26,
position: "Frontend",
},
{
userUuid: "bbb123",
name: "둘리",
age: 33,
position: "Backend",
},
{
userUuid: "ccc123",
name: "마이콜",
age: 30,
position: "UX,UI",
},
];
dataA 의 author, userUuid 와 dataB 의 name, userUuid 값을 매칭한다.
비교 연산은 대략 아래처럼
dataA.author === dataB.name && dataA.userUuid === dataB.userUuid
먼저 dataA 를 기반으로 한 목록구현
<ul>
{dataA.map((item) => {
return (
<li
key={item.id}
>
<h4>{item.title}</h4>
<div>{item.body}</div>
<div>
작성자: {item?.author}
</div>
</li>
);
})}
</ul>

게시물 목록에 유저정보 데이터인 dataB 를 합쳐보자
<ul>
{dataA.map((item) => {
const authorData = dataB.find(
(b) =>
item.author === b.name &&
item.userUuid === b.userUuid,
);
return (
<li
key={item.id}
>
<h4>{item.title}</h4>
<div>{item.body}</div>
<div>
작성자: {item?.author} ({authorData?.age} / {authorData?.position})
</div>
</li>
);
})}
</ul>
dataA,B 를 비교하는 find 로직이 추가되고 유저정보를 추가로 바인딩 해 줌
const authorData = dataB.find((b) => item.author === b.name && item.userUuid === b.userUuid,);
Array 인스턴스의 find 메서드를 살펴보면 아래와 같이 설명한다.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Thefind()method ofArrayinstances returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function,undefinedis returned.find(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): T | undefined;
- 제공된 배열에서 제공된 테스트 함수를 만족하는 첫 번째 요소를 반환한다. 테스트 함수를 만족하는 값이 없으면 undefined 가 반환 됨.
