[React] 객체 반복문

김하영·2023년 2월 26일
0

React

목록 보기
7/7
post-thumbnail

객체 반복문?

리액트를 사용하다보면 주로 배열을 이용해 반복문을 돌린다.
예를 들면

const arr = [
	{id: 0, name: 'hayeong', age: 27},
    {id: 1, name: 'onew', age: 1}
]

const index = () => {
	return (
    	<ul>
        	{arr.map(item => (
            	<li key={item.id}>{item.name}</li>
            ))}
        </ul>
    )
}

이러한 경우다.

그렇다면 객체로 반복문을 돌릴 수는 없을까?

당연히 가능하다. Object.keys를 이용하자.

const obj = {
	first: 'hayeong',
    second: 'onew'
}

const index = () => {
	return (
    	<ul>
        	{Object.keys(obj).map(key => (
            	<li key={key}>{obj[key]}</li>
            ))}
        </ul>
    )
}

그렇다면 키(key)가 있는 객체는 어떻게 돌릴까?

const keyObj = {
	first: [
    	{id: 0, name: 'hayeong', age: 27},
    	{id: 1, name: 'onew', age: 1}
    ],
    second: [
    	{id: 0, name: 'hayeong', age: 27},
    	{id: 1, name: 'onew', age: 1}
    ]
}

const index = () => {
	return (
    	<ul>
        	{keyObj[Object.keys(keyObj)].map(item => (
            	<li key={item.id}>{item.name}</li>
            ))}
        </ul>
    )
}
profile
호기심 많은 프론트엔드 주니어 💡

0개의 댓글