Lodash, javascript 필수 라이브러리 메서드

김민아·2023년 1월 17일

Lodash

Lodash는 자바스크립트 유틸리티 라이브러리 중 하나로, 배열, 객체, 문자열 등 다양한 자료형을 다룰 수 있는 메서드를 제공한다. cross-browser 호환성 문제와 일관성있는 동작을 보장하기 위해 사용한다. 배열 내장 메서드보다 유연한 메서드 체이닝을 제공하여 코드를 간편하게 작성할 수 있다.

메서드 체이닝 (method chaining)이란?

여러 메서드를 연결해서 연속적으로 처리하는 것을 의미한다.
1. 중복된 코드를 줄일 수 있다.
2. 중간 결과를 저장하지 않고 연속적으로 처리한다.
3. 지나치게 길어지면 가독성에 좋지 않고, 디버깅이 어려워질 수 있다.

const result = numbers
  .filter(num => num % 2 === 0) // 짝수만 필터링
  .map(num => num * 2);         // 2배씩 곱해서 변환

✨설치

$ npm i -g npm
$ npm i --save lodash

배열 (array)

배열만을 다루기 보다 복합적인 콜렉션 데이터를 사용할 때 lodash 라이브러리를 유용하게 사용하는 것 같다.

_.map(collection, [iteratee=_.identity])

배열의 요소를 순회하며 각 요소를 변환한 새로운 배열을 반환한다.

const numbers = [1, 2, 3, 4];
const squares = _.map(numbers, n => n * n);
// squares: [1, 4, 9, 16]

_.filter(collection, [predicate=_.identity])

배열의 요소를 순회하며 조건에 맞는 요소만을 필터링한 새로운 배열을 반환한다.

const numbers = [1, 2, 3, 4];
const evens = _.filter(numbers, n => n % 2 === 0);
// evens: [2, 4]

_.reduce(collection, [iteratee=_.identity], [accumulator])

배열의 요소를 순회하며 각 요소를 이용해 값을 누적하거나 연산한 결과를 반환한다.

const numbers = [1, 2, 3, 4];
const sum = _.reduce(numbers, (acc, n) => acc + n, 0);
// sum: 10

_.find(collection, [predicate=_.identity], [fromIndex=0])

배열에서 조건에 맞는 첫번째 요소를 반환한다.

const numbers = [1, 2, 3, 4];
const even = _.find(numbers, n => n % 2 === 0);
// even: 2

_.sortBy(collection, [iteratees=[_.identity]])

배열의 요소를 기준으로 정렬한 값을 반환한다.

const people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 20 }
];
const sorted = _.sortBy(people, 'age');
// sorted: [
// { name: 'Charlie', age: 20 }, 
// { name: 'Alice', age: 25 }, 
// { name: 'Bob', age: 30 }]

_.groupBy(collection, [iteratee=_.identity])

배열의 요소를 그룹화한다.

const people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 20 }
];
const grouped = _.groupBy(people, 'age');
// grouped = { '20': [{ name: 'Charlie', age: 20 }], '25': [{ name: 'Alice', age: 25 }], '30': [{ name: 'Bob', age: 30 }] }

_.forEach(collection, [iteratee=_.identity])

배열의 각 요소에 대해 함수를 실행한다.

const numbers = [1, 2, 3, 4];
_.forEach(numbers, n => console.log(n));
// 출력 결과: 1 2 3 4

객체 (object)

_.get(object, path, [defaultValue])

객체의 경로에 따라 value를 반환한다.

const obj = { a: { b: { c: 1 } } };
const value = _.get(obj, 'a.b.c');
console.log(value); // 1

_.set(object, path, value)

객체의 경로에 value를 설정한다.

const obj = { a: { b: { c: 1 } } };
_.set(obj, 'a.b.c', 2);
console.log(obj); // { a: { b: { c: 2 } } }

_.assign(object, [sources])

객체를 병합하여 새로운 객체를 반환한다.

function Foo() {
  this.a = 1;
}
 
function Bar() {
  this.c = 3;
}
 
Foo.prototype.b = 2;
Bar.prototype.d = 4;
 
_.assign({ 'a': 0 }, new Foo, new Bar);
// => { 'a': 1, 'c': 3 }

_.clone(value)

객체를 복사(얕은)하여 새로운 객체를 반환한다.

var objects = [{ 'a': 1 }, { 'b': 2 }];
 
var shallow = _.clone(objects);
console.log(shallow[0] === objects[0]);
// => true

_.cloneDeep(value)

재귀적으로 객체를 깊은 복사를 하여 새로운 객체를 반환한다.

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

_.pick(object, [paths])

객체에서 지정한 속성만을 추출하여 새로운 객체를 반환한다.

var object = { 'a': 1, 'b': '2', 'c': 3 };
 
_.pick(object, ['a', 'c']);
// => { 'a': 1, 'c': 3 }

함수 (function)

_.bind(func, thisArg, [partials])

greetingperson을 바인딩하면 greetingthisperson 객체가 된다. 부분 인자를 미리 바인딩하고 호출할 때 나머지를 전달하는 것이 가능하다.

const greeting = function(message, punctuation) {
  return `${message} ${this.name}${punctuation}`;
}

const person = { name: 'John' };

const boundGreeting = _.bind(greeting, person, 'Hello');

console.log(boundGreeting('!')); // 출력 결과: Hello John!

greeting의 첫번째 인자인 message_로 미룰 수 있다.

const greetWithGreeting = _.bind(greeting, person, _, '!');

console.log(greetWithGreeting('Hello')); // 출력 결과: Hello John!

_.debounce(func, [wait=0], [options={}])

연속된 이벤트를 일정 시간(wait) 동안 경과 후 마지막 이벤트를 처리하는 함수를 반환합니다.

const searchInput = document.getElementById('search-input');

function search() {
  // 검색 기능 수행
}

// 입력이 멈출 때 500ms 후 검색 함수 실행
const debouncedSearch = _.debounce(search, 500);

searchInput.addEventListener('input', debouncedSearch);

lodash 라이브러리는 자바스크립트의 다양한 자료형을 다루는 메서드를 제공하여 생산성을 높여준다. Lodash 라이브러리의 활용 방법을 숙지하면 코드를 더 간결하게 작성할 수 있으며, 불필요한 중복 코드를 줄일 수 있다.

출처

0개의 댓글