Notice
Recent Posts
Recent Comments
Link
250x250
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 | 31 |
Tags
- 동적객체
- 정적객체
- package.json
- maxwidth
- 아이콘사용법
- window 정책변경
- npm install
- 단어단위로떨어지기
- npm start
- vscode git clone
- minwidth
- 이미지반응형
- MediaQuery
- 웹아이콘
- node 오류
- 글자들여쓰기
- git lab clone
- 의존성문제
- npm install 문제
- legacy-peer
- fontawesome
- react npm install
- Git clone
- 플러그인
- 그누보드반응형
- owlcarousel
- XEIcon
- node설치
- googleicon
- slickslider
Archives
- Today
- Total
어쩌다 알게 된 ƪ(•̃͡•̃͡ ƪ
🟦 [React] 배열 반환할 때, 타입이 달라도 무조건적으로 배열 가져오기 본문
728x90
| 메서드 | 설명 | 반환값 |
| Array.isArray(value) | value 값이 배열인지 확인 | true, false |
| Object.values(obj) | 객체의 값들만 배열로 반환 (배열, 숫자, null 같은 비객체에는 사용 불가) |
배열 => [ "값1", "값2" ... ] |
| 예제 1) 기본형 |
const person = { name: "John", details: { age: 30, city: "New York" } }; console.log(Object.values( person.details )); => [30, "New York"] |
|
| 예제 2) map() 사용 변환 |
const scores = { math: 90, english: 80, science: 85 }; const scoreList = Object.values(scores).map(score => `점수: ${score}`); console.log(scoreList); => ["점수: 90", "점수: 80", "점수: 85"] |
|
| 예제 3) join() 사용 문자열 변환 |
const person = { firstName: "Kim", lastName: "Minseo", age: 28 }; console.log(Object.values(person).join(", ")); => "Kim, Minseo, 28" |
|
| Object.key(obj) | 객체의 key값을 배열로 반환 | 배열 => ["key값1", "key값2"] |
| 예제 1) | const user = { name: "Alice", age: 25, city: "Seoul" }; console.log(Object.keys(user)); => ["name", "age", "city"] |
|
| 예제 2) | const arr = ["apple", "banana", "cherry"]; console.log(Object.keys(arr)); => ["0", "1", "2"] => 배열일 경우 키 값이 없으므로 index 값이 문자열로 반환됨 |
|
| Object.entries(obj) | 객체의 키-값 쌍 형태 key, value를 배열로 반환 |
배열 => [ [ "키값1", "값1" ], ["키값2", "값2" ] ] |
| 예제 1) | const user = { name: "Alice", age: 25 }; console.log(Object.entries(user)); => [ ["name", "Alice"], ["age", 25] ] |
|
| Object.fromEntries(obj) |
배열을 객체로 반환 => entries와 반대 |
객체 => { 키1: 값1, 키2: 값2 } |
| 예제 1) | const entries = [["name", "Alice"], ["age", 25]]; console.log(Object.fromEntries(entries)); => { name: "Alice", age: 25 } |
❗ Object로 시작하는 메소드들은 null 값이나 undefined 값을 주게 되면 오류가 발생 ❗
=> ex) Object.values(null) ❌
| 해결 방법 1️⃣ | 해결 방법 2️⃣ |
| || {} (기본 객체를 제공) | ?. (옵셔널 체이닝) |
| const data = null; console.log(Object.keys(data || {})); // [] (에러 없이 빈 배열 반환) |
const data = null; console.log(Object.keys(data)?.length); // undefined (에러 없이 실행) |
| => data가 null이면 {}(빈 객체)로 대체해서 에러 방지! | => ?.(옵셔널 체이닝)을 사용하면 null이나 undefined일 때 에러 없이 undefined 반환 |
여기부분이 어떤 타입이든 배열로 반환하여 뿌리는 코드 👇
<td>
{(typeof data.link === "string" // 문자열인지 구분하여 true면 배열로 반환
? [data.link]
: Array.isArray(data.link) // 배열인지 구분하여 true면 그대로 반환
? data.link
: Object.values(data.link) // 문자열과 배열이 아니면(객체라고 간주) 값을 배열로 변환
).map((link, index) => (
<a key={index} href={link}>{link}</a>
))}
</td>
react를 구현하면서 js를 더 많이 공부해야겠다는 생각을 한다................

✅ 구현하고 싶던 것: 데이터가 tabData.js 처럼 있을 때, link 키의 배열 값을 하나하나 가져오고 싶었다.
tabData.js 👇
const tabData = {
ui: [
{
section: "메인",
modifyFiles: [
{
type: "html",
files: [
"src>main.html"
]
},
{
type: "js",
files: [
"src>main.js"
]
},
{
type: "css",
files: [
"src>test.css",
"src>test.min.css",
]
}
],
image: "img/250306_main.PNG",
link: [
"https:www.naver.com/",
"html/index.html"
],
notice: "분기처리 해야 했음",
annotation: [
"법인 삭제",
"[hb] 250306 법인명으로 분기처리 되어 있던 부분 통합 처리"
],
requestor: "250306 완료"
},
{
section: "메인222",
modifyFiles: [
{
type: "html",
files: [
"src>main.html"
]
},
{
type: "js",
files: [
"src>main.js"
]
},
],
image: "img/250306_main.PNG",
link: [
"https://www.naver.com"
],
notice: "알림사항2",
annotation: [
"확인"
],
requestor: "250306"
},
],
}
Tab.jsx 👇
import { useState } from "react";
import { tabName, tabTh, tabData } from "../data/tabData";
export default function TabComponent(){
// tab-list
const [activeTab, setActiveTab] = useState(0) // 현재 선택된 탭의 index
const handleTabClick = (index) => {
setActiveTab(index);
}
// tab-con-list
const tabDataKey = Object.keys(tabData);
const tabThKey = Object.keys(tabTh);
return(
<>
<ul className="tab-list">
{
tabName.map((tab, index) => (
<li key={index}
className={activeTab === index ? "active" : ""}
><button onClick={() => handleTabClick(index)}>{tab}</button>
</li>
))
}
</ul>
<div className="tab-con-list">
{tabName.map((tab, index) => (
<div key={index}
className={`tab-con ${activeTab === index ? "active" : ""}`}
>
<table>
<colgroup>
<col width="5%" />
<col width="25%" />
<col width="10%" />
<col width="25%" />
<col width="20%" />
<col width="10%" />
<col width="5%" />
</colgroup>
<thead>
<tr>
{activeTab == tabName.length - 1
? tabTh[tabThKey[1]].map((th, index) => (
<th key={index}>{th}</th>
))
: tabTh[tabThKey[0]].map((th, index)=> (
<th key={index}>{th}</th>
))
}
</tr>
</thead>
<tbody>
{tabData[tabDataKey[index]].map((data, dataIndex) => (
<tr key={dataIndex}>
<td>{data.section}</td>
{/* 존재하면 수행 */}
<td>
{data.modifyFiles?.map((fileData, index) => (
<div key={index}>
<strong>[ {fileData.type} ]</strong><br/>
{fileData.files.join("<br/>")}
<br/><br/>
</div>
))}
</td>
<td><a href={data.image}></a></td>
<td>
{(typeof data.link === "string" // 문자열인지 구분하여 true면 배열로 반환
? [data.link]
: Array.isArray(data.link) // 배열인지 구분하여 true면 그대로 반환
? data.link
: Object.values(data.link) // 문자열과 배열이 아니면(객체라고 간주) 값을 배열로 변환
).map((link, index) => (
<a key={index} href={link}>{link}</a>
))}
</td>
<td></td>
<td></td>
<td></td>
</tr>
))}
</tbody>
</table>
</div>
))}
</div>
</>
)
}728x90
'개발 > 🟦 React' 카테고리의 다른 글
| 🟦 [React] onClick={함수}, {함수()}, {() => 함수}, {() => 함수()} 차이 (0) | 2025.03.20 |
|---|---|
| 🟦 [React] 텍스트 불러올 때 <br /> 사용하기 => <React.Fragment> 이용 (0) | 2025.03.20 |
| 🟦 [React] 삼항 연산자 사용법 (0) | 2025.03.19 |
| 🟦 [React] 중첩된 객체와 배열 구조 => 가지고 오고 싶은 값 사용하기 (0) | 2025.03.18 |
| 🟦 [React] onclick={함수()}, onclick={() => 함수()} 차이점 (0) | 2025.03.18 |
Comments
