FrontEnd/Javascript
[ Javascript ] Lodash 기능 사용하기
jimin-log
2023. 8. 14. 18:01
Lodash 기능 사용하기
기본 통로를 사용해서 가져온다.
import _ from 'lodash'
1. 중복 제거
1-1 .중복내용 제거
.uniq()
_.uniq([2,1,2]);
1-2 .중복 배열 내용 고유하게 만들기.
_.uniqBy(중복 배열 데이터 ,고유 속성)
const usersA = [
{userId : '1', name : 'HEROPY'},
{userId : '2', name : 'Neo'}
]
const usersB = [
{userId : '1', name : 'HEROPY'},
{userId : '3', name : 'Amy'}
]
//배열 합치기
const usersC = userA.concat(usersB);
console.log(usersC);
//결과 : {userId : '1', name : 'HEROPY'},{userId : '2', name : 'Neo'},{userId : '1', name : 'HEROPY'},{userId : '3', name : 'Amy'}
//고유값 userId 라고 했을때, 중복재거
console.log(_.uniqBy(usersC,'userId'));
1-3 . 여러개의 배열 고유하게 합치기
_.uniqBy(배열1,배열2,고유 속성)
const usersD = _.unionBy(usersA,userB,'userId');
2. 일치 객체출력 및 제거
const users = [
{userId:'1', name: 'heropy'},
{userId:'2', name: 'neo'},
{userId:'3', name: 'amy'},
{userId:'4', name: 'evan'},
{userId:'5', name: 'lewis'}
]
2-1. 일치하는 객체 찾기
_.find(배열, 찾는내용)
const foundUser = _.find(users, {name : 'amy'});
console.log(foundUser);
//결과값 : {userId:'3', name: 'amy'}
2-2. 인덱스 번호 반환
_.findIndex(배열, 찾는내용)
const foundUserIndex = _.findIndex(users, {name : 'amy'});
console.log(foundUserIndex);
//결과값 : 3
2-3. 원하는 객체 제거
_.remove(배열, 찾는내용)
const foundUserIndex = _.remove(users, {name : 'amy'});
이외의 Lodash 메서드 사용방법은 아래 링크에서 확인 가능합니다.
Lodash
_.defaults({ 'a': 1 }, { 'a': 3, 'b': 2 });_.partition([1, 2, 3, 4], n => n % 2);DownloadLodash is released under the MIT license & supports modern environments. Review the build differences & pick one that’s right for you.InstallationIn
lodash.com