본문 바로가기
💻CODING/javascript

[js] lodash 사용법, 자주 쓰는 메소드

by 코딩하는 갓디노 2021. 6. 30.

lodash

 

자바스크립트 라이브러리, 
lodash 사용법입니다. 

 

lodash란

  • Lodash는 자바스크립트 라이브러리로서, 객체, 배열 등의 데이터의 구조를 쉽게 변환하여 사용하게끔 도와줍니다.
  • 실무에서 데이터를 handling 할때 복잡한 자바스크립트 코드를 lodash를 사용함으로 인하여 보다 빠른 작업과 간결한 코드를 사용할 수 있게 됩니다. 
  • _ 라는 기호를 사용하여 명칭이 lodash 입니다. 
  • 배열에서 중복값을 제거할때, uniqBy, unionBy 메소드를 사용합니다.
  • 배열에서 원하는 객체 데이터를 추출할 때, find 메소드를 사용하고, 제거할 때는 remove 메소드를 사용합니다. 
  • 깊은 복사를 사용할 경우, cloneDeep 메소드를 이용합니다. 

 

lodash 설치

lodash 홈페이지 installation에 설치 방법에 나와있습니다. 

https://lodash.com/

 

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

 

cdn 설치 방법

<script src="lodash.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

 

npm  설치 방법

import 할때,  { } 로 감싸지 않을 경우, 통상적으로 _ 로 하나,  _ 대신 아무 이름이나 지정이 가능합니다.

//npm 설치
npm i -g npm
npm i --save lodash

//import
import _ from 'lodash';

 

lodash 메소드

uniqBy

  • 배열 데이터 안의 값에서 중복 되는 값들을 제거한 후 반환합니다.
  • 배열 데이터가 하나일 때 사용합니다.
_.uniqBy(배열 변수, '고유한 속성의 이름')

 

unionBy

  • unioqBy와 비슷한 기능인데, uniqBy는 합친 후의 배열 데이터이고,
    unionBy는 합치기 전 배열의 데이터를 합쳐서, 중복 되는 값을 제거한 후 반환합니다. 
  • 배열 데이터가 여러개 일 때 사용합니다. 
_.unionBy(배열 변수1, 배열 변수2, '고유한 속성의 이름')

 

uniqBy, unionBy 예제

const fruit1 = [
	{ fruitId: 1, color: "yellow", name: "banana"}, 
	{ fruitId: 2, color: "green", name: "apple" }
]
const fruit2 = [
	{ fruitId: 2, color: "green", name: "apple" }, 
	{ fruitId: 3,color: "red", name: "strawberry" }
]

const total = fruit1.concat(fruit2); //하나로 병합
console.log('total', total);
console.log('uniqBy', _.uniqBy(total, 'fruitId')); //중복 값 제거

const fruit3 = _.unionBy(fruit1, fruit2, 'fruitId');
console.log('unionBy', fruit3);
//결과
total (4) [{…}, {…}, {…}, {…}]
0: {fruitId: 1, color: "yellow", name: "banana"}
1: {fruitId: 2, color: "green", name: "apple"}
2: {fruitId: 2, color: "green", name: "apple"}
3: {fruitId: 3, color: "red", name: "strawberry"}
length: 3
uniqBy (3) [{…}, {…}, {…}]
0: {fruitId: 1, color: "yellow", name: "banana"}
1: {fruitId: 2, color: "green", name: "apple"}
2: {fruitId: 3, color: "red", name: "strawberry"}
length: 3
unionBy (3) [{…}, {…}, {…}]
0: {fruitId: 1, color: "yellow", name: "banana"}
1: {fruitId: 2, color: "green", name: "apple"}
2: {fruitId: 3, color: "red", name: "strawberry"}
length: 3

 

find

배열 안에서 특정한 객체 데이터만 찾아서 반환합니다. 

_.find(배열, { 찾을 객체 데이터 });

 

findIndex

배열 안에서 특정한 객체 데이터의 index를 반환합니다. 

_.findIndex(배열, { 찾을 객체 데이터 });

 

find, findIndex 예제

const fruits = [
	{ fruitId: 1, name: "banana"}, 
	{ fruitId: 2, name: "apple" },
 	{ fruitId: 3, name: "strawberry"}, 
	{ fruitId: 4, name: "melon"}, 
	{ fruitId: 5, name: "kiwi" },
]

const checkedFruit = _.find(fruits, {name: 'kiwi'});
console.log('checkedFruit', checkedFruit);

const checkedFruitIdx = _.findIndex(fruits, {name: 'kiwi'});
console.log('checkedFruitIdx', checkedFruitIdx);
//결과
checkedFruit {fruitId: 5, name: "kiwi"}
checkedFruitIdx 4

 

remove

배열에서 원하는 객체 데이터를 제거한 후 반환합니다 .

_.remove(배열, { 제거할 객체 데이터 });

 

remove 예제

const fruits = [
	{ fruitId: 1, name: "banana"}, 
	{ fruitId: 2, name: "apple" },
  { fruitId: 3, name: "strawberry"}, 
	{ fruitId: 4, name: "melon"}, 
	{ fruitId: 5, name: "kiwi" },
]

_.remove(fruits, {name: "melon"});
console.log(fruits);
//결과
(4) [{…}, {…}, {…}, {…}]
0: {fruitId: 1, name: "banana"}
1: {fruitId: 2, name: "apple"}
2: {fruitId: 3, name: "strawberry"}
3: {fruitId: 5, name: "kiwi"}
length: 4

 

cloneDeep 

배열 안의 데이터를 깊은 복사하는 사용합니다.

_.cloneDeep(value)

 

cloneDeep 예제

const objects = [{ 'a': 1 }, { 'b': 2 }];
 
const deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false 
반응형

댓글