검색 결과 나오는 방법: 제품 검색 시 하위목록까지 나오게 하는 법

나는야 토마토·2022년 2월 25일
0

기능정리🧙

목록 보기
1/8
post-thumbnail

hooks - useSearch.js

위 이미지를 보면 드레스 or 원피스를 입력한 후 나오는 예시이다.
이 때 product.json데이터 형식이 아래와 같다. 원피스로 키워드를 입력 시에는 name에 있는 변수에 포함되어 있는지 includes()함수를 통해 확인하면 되지만 드레스를 입력할 경우에는 다르게 작성하였다.

{
    "product_code": 2,
    "name": "원피스_019",
    "image_url": "https://static.pxl.ai/problem/images/OP-019.jpg",
    "price": 34592,
    "category_names": [
      "c1.onepiece",
      "c2.dresses",
      ""
    ]
  },

includes() 사용

만약 word원피스로 입력할 경우

products.filter((product) => product.name.includes(word) 

에 의해서 아래와 같은 데이터가 출력되어진다.

{
    "product_code": 2,
    "name": "원피스_019",
    "image_url": "https://static.pxl.ai/problem/images/OP-019.jpg",
    "price": 34592,
    "category_names": [
      "c1.onepiece",
      "c2.dresses",
      ""
    ]
  },

추가적으로 keyword에 입력했을 경우에 나타날 데이터와 image_url을 입력했을 때 나타날 데이터 로직이 다를 수 있으므로, type으로 비교해서 팀원 분이 작성해주셨다!
그 부분을 활용해서 name에 대한 로직을 다음과 같이 작성한 후,

// name에 대한 로직
const keywordName = (product, word) => product.name.includes(word);

category_names 부분 로직과 이어주었다!

category_names에 대해 비교하기 위해선 배열 안에 있는 값을 하나씩 나올 수 있게 작성해야한다.
이 때에는 for of 함수를 이용해서 배열에 있는 데이터 값이 나올 수 있게 작성하였고, .을 기준으로 split를 해주었다.

const keywordCategory = (product, word) => {
  const keyword = changeName(word);
  for (let cate of product.category_names) {
    let category = cate.split('.');
    if (category[1] === keyword) {
      return category[1];
    }
  }
};

이 때 영문으로 된 카테고리 즉, dresses랑 사용자가 한글로 입력한 키워드 드레스를 비교하기 위해서는 switch-case문을 이용하여 한글로 입력한 키워드를 영문으로 바꿀 수 있게 하였다.

// 한글로 입력된 input값, 영문으로 변경
const changeName = (keyword) => {
  switch (keyword) {
    case '원피스':
      return 'onepiece';
    case '드레스':
      return 'dresses';
    case '조끼':
      return 'vests';
    case '자켓':
      return 'jackets';
    case '바지':
      return 'pants';
    case '상의':
      return 'tops';
    case '하의':
      return 'bottoms';
    case '코트':
      return 'coats';
    case '점퍼':
      return 'outwears';
    case '니트':
      return 'knitwear';
    case '셔츠':
      return 'shirts';
    case '스웨터':
      return 'sweater';
    case '신발':
      return 'shoes';
    case '치마':
      return 'skirts';
    default:
      return keyword;
  }
};

이 두 부분을 합쳐주니 사용자가 상의를 입력했을 경우, 자켓, 코트, 점퍼 등에 대한 카테고리도 함께 나올 수 있었다.!

직접 확인해보기!

가장 어려웠던 점은 한글로 입력된 input의 값을 영어로 바꾸어서 카테고리 배열에 있는 지 확인하는 부분과 카테고리 배열로 접근하는 방법이 어려웠다...!!!

profile
토마토마토

0개의 댓글