devlog_zz

string to array javascript / filter is not a function 오류 본문

카테고리 없음

string to array javascript / filter is not a function 오류

YJ_SW 2020. 12. 7. 11:22
728x90

axios로 API를 호출하여 데이터를 받아와 바로 저장하였을 때

데이터의 type에 대해 주의해야한다.

 

log로 찍어 봤을 때, ['aaa','bbb','ccc'] 와 같이 나와 배열형태인줄 알고 개발을 진행하였다.

근데 res.filter를 적용하였을 때, filter is not a function 오류가 발생하였다.

 

이럴 때 먼저 filter를 적용한 변수의 type을 먼저 알아보자

typeof(res) 

이 때, object가 나오지 않고 string이 나와 잘못된 것을 알게 되었다.

참고 자바스크립트에서는 typeof(data) 하여도 object가 결과로 나옴

배열인지 확인하려면 Array.isArray(data) 를 통해 확인해야함

 

stirng => array로 바꾸기

내 경우는 배열 형태의 string인 경우를 array 형태로 바꿔야 헀다.

 

2) 다른 해결 방법

https://stackoverflow.com/questions/41402834/convert-string-array-to-array-in-javascript

 

Convert string array to array in javascript

I get the following item back from my django-rest-framework api call: services = "['service1', 'service2', 'service3']" I want services = ['service1', 'service2', 'service3'] In my JavaScript I ...

stackoverflow.com

['aaa','bbb','ccc']

를 ["aaa","bbb","ccc"] 

큰 따옴표로 대체해야 JSON.parse 가능함

 

728x90
Comments