https://stackoverflow.com/questions/16037049/why-does-javascript-map-function-return-undefined
방금 그 건이 그렇게 잘 마무리 된 줄 알았으나 아니었다.
내가 잘 이해한 것인지 모르겠는데 filter는 기존 배열에서 거르는 작용을 하는 것 뿐이기에
기존 대상 내부에서는 가져올 수 있어도 그 외의 첨부 요소를 가져다가 붙여서 새로운 형체를 만들 순 없는 것 같다.
그래서 기존 값에 추가되어야 하는 요소가 있었던 나는 그냥 기존
map을 활용하되, map으로 가져온 값에서 filter로 undefiend를 걸러내는 식으로 일단 코드를 수정했다.
const notUndefined = anyValue => typeof anyValue !== 'undefined'
const noUndefinedList = someList
.map(// mapping condition)
.filter(notUndefined); // by doing this,
//you can ensure what's returned is not undefined
처음엔 이 코드를 참고했는데
filter(Boolean)이라는 좀 더 간결한 방식을 찾아내서 이걸 활용했다.
앞으로도 빈값 걸러낼 때 요긴하게 쓸 수 있을듯?
const arr = ['a','b',1]
const result = arr.map(element => {
if(typeof element === 'string')
return element + ' something'
}).filter(Boolean) // this will filter out null and undefined
console.log(result) // output: ['a something', 'b something']
https://velog.io/@yongbum/filter-boolean
Boolean을 iterator 로 사용하여 false, 0, -0, 0n, "", null, undefined, NaN를 제거할 수 있다.
'오늘은 공부 중 > 자바스크립트' 카테고리의 다른 글
[Javscript] map함수를 쓰면 undefined가 저장, 반환될 때 (0) | 2022.02.23 |
---|---|
[자바스크립트] 얕은 복사, 깊은 복사. assign, 스프레드 연산자 (0) | 2021.09.23 |
자바스크립트 라이브러리, loadash & underscore. 객체 배열로 바꾸기 (0) | 2021.09.23 |
[Nest.js] 넌 또 누구니 (0) | 2021.09.14 |
[Joi] TopLevelDomainOptions : { tlds: { allow: true } } (0) | 2021.09.08 |