typeerror: cannot read properties of undefined (reading 'push') 해결하기

Maliethy·2021년 9월 17일
0

javascript error

목록 보기
3/5

1. issue

let optLists = [];

	const  options= [
      {
        "id": 4816080660,
        "optionType": "COMBINATION",
        "groupName": "컬러"
      },
      {
        "id": 4816080661,
        "optionType": "COMBINATION",
        "groupName": "사이즈"
      }
    ];
    
    const optionCombinations= [
      {
        "id": 16902168773,
        "optionName1": "블랙",
        "optionName2": "대",
       },
      {
        "id": 16902168775,
        "optionName1": "블랙",
        "optionName2": "소",
      },
      {
        "id": 16902168776,
        "optionName1": "레드",
        "optionName2": "대",
      },
      {
        "id": 16902168777,
        "optionName1": "레드",
        "optionName2": "중",
      },
      {
        "id": 16902168778,
        "optionName1": "레드",
        "optionName2": "소",
      }
    ];
      

위와 같은 데이터 구성에서 options의 groupName 별로 optionCombinations의 optionName1과 optionName2을 짝짓고 싶은 경우이다.
결과물이 색상: 검정 / 사이즈: 대, 색상: 검정 / 사이즈: 소, 색상: 레드 / 사이즈: 대, 색상: 레드 / 사이즈: 소로 나오면 된다.
options의 index와 optionName 뒤의 번호를 일치시켜 새로운 배열 arr에 넣으려 다음과 같은 로직을 짰더니 optLists[key].push 부분에서 typeerror: cannot read properties of undefined (reading 'push') 가 발생했다.

            list.options.forEach((option, idx) => {
              list.optionCombinations.map((combination, key) => {
                if (list.options.length - 1 === idx) {
                  optLists[key].push(`${option.groupName}: ${combination[`optionName${idx + 1}`]}`);
                } else {
                  optLists[key].push(`${option.groupName}: ${combination[`optionName${idx + 1}`]} / `);
                }
              });
            });

2. solution

optLists[key]가 undefined이기 때문에 Array의 protoType인 push method를 쓸 수 없다는 에러이다. 다음과 같이 optLists[key] 부분에 배열을 할당해주면 에러가 해결된다.

 for (let key in list.optionCombinations) {
              optLists[key] = [];
            }
profile
바꿀 수 있는 것에 주목하자

0개의 댓글