lodash?
- JS(JavaScript)의 라이브러리 중 하나로 설치하여 사용할 수 있다.
- _ 기호를 사용한다
- 데이터를 쉽게 다룰 수 있게 한다.
- frontend에서 자주 사용하며 코드를 줄여주고 빠른 작업이 가능하다.
npm, yarn 으로 설치
npm i -g npm
npm i --save lodash
yarn add lodash
공통으로 사용할 테스트 변수
const fruits1 = [
{name:"kiwi",color:"green",count:2},
{name:"banana",color:"yellow",count:5},
{name:"apple",color:"green",count:2},
{name:"apple",color:"red",count:3}
]
const fruits2 = [
{name:"strawberry",color:"red",count:1},
{name:"grape",color:"purple",count:1}
]
메소드
uniqBy
- 배열 데이터에서 기준이 되는 키의 중복 값 제거 후 반환
_.uniqBy(fruits1, 'color')
// color가 중복되는 데이터가 제거됨
// [{name:"kiwi",color:"green",count:2},{name:"banana",color:"yellow",count:5},{name:"apple",color:"red",count:3}]
unionBy
- 2개 이상의 배열 데이터에서 기준이 되는 키의 중복 값 제거 후 합쳐진 리스트로 반환
_.unionBy(fruits1, fruits2, 'name')
// 두 배열에서 name이 중복되는 값이 제거됨, fruits3이 있다면 뒤에 더 넣을 수 있음
// [{name:"kiwi",color:"green",count:2},{name:"banana",color:"yellow",count:5},{name:"apple",color:"green",count:2},{name:"strawberry",color:"red",count:1},{name:"grape",color:"purple",count:1}]
find
- 배열에서 특정 객체를 찾아 반환
_.find(fruits1, {name: "banana"})
// name이 같은 데이터를 찾아 반환
// {name:"banana",color:"yellow",count:5}
findIndex
- 배열에서 특정 객체를 찾아 index(number)를 반환
_.findIndex(fruits1, {name: "banana"})
// name이 같은 데이터를 찾아 index 반환
// 1
remove
- 배열에서 특정 객체를 찾아 제거한 후 리스트로 반환
_.remove(fruits1, {name: "apple"})
// name이 같은 데이터를 찾아 제거한 후 리스트 반환
// [{name:"kiwi",color:"green",count:2},{name:"banana",color:"yellow",count:5}]