2차 프로젝트 술고 에서의 userData의 형식은 다음과 같이 서버에서 불러와진다.
{
"result": {
"id": 1,
"text_name": "오동녘어진이",
"text_email": "wecode@wecodebootcamp.com",
"profile_image_url": "/images/mangorookie.jpeg",
"text_gender": "남",
"text_mbti_title": "INFP",
"text_mbti_description": "소심한 관종",
"text_class_number": 27,
"text_stack": "프론트",
"text_comment": "삼겹살에 쐬주 한잔 하고 싶네요",
"text_favorite_place": "경기도 뉴욕시",
"text_favorite_food": "막창",
"text_favorite_hobby": "농구",
"alcohol_limit": {
"반병": true
},
"alcohol_level": { "11도 ~ 20도": true },
"alcohol_drinking_methods": [{ "온더락": true }, { "폭탄주": true }],
"alcohol_categories": [
{ "와인": true },
{ "진": false },
{ "위스키": true }
],
"alcohol_flavors": [
{
"싱그러운": true
},
{
"묵직": true
},
{
"달콤": true
},
{
"고소": true
}
]
}
}
이때 key에 "alcohol_" 로 시작하는 데이터들은 배열안의 배열로 관리되는 편이 좋을 것 같아서 가공을 해보았고,
생각보다 가공할 때 로직 공부하던게 재밌었고 도움이 많이 되어 기록으로 남겨본다.
function filterTagFromUserData(userData) {
const tag = Object.values(userData).flat(Infinity);
const arr = tag.filter(el => typeof el === 'object');
const arr2 = arr.map(el => Object.keys(el));
const arr3 = arr2.flat(Infinity);
return arr3;
}
먼저 userData를 infinity depth로 배열 형태로 flat 메서드를 통해 만든다.
다음으로 배열 안의 객체들만 뽑아서 arr 이란 변수에 저장한다.
다음으로 그 객체 안의 key만 뽑아서 arr2 라는 변수에 저장한다.
마지막으로 arr2 배열을 infiniy depth로 flat시켜주면
[ '반병', '11도 ~ 20도', '온더락', '폭탄주', '와인', '진', '위스키', '싱그러운', '묵직', '달콤' ]
와 같은 형태로 return 된다.
객체 안의 배열 안의 객체 형태에서 하나의 depth로 이루어진 배열로 만들기에 유용한 함수라고 생각된다.