Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

다재다능 개발자 성장기 🚀

lodash 라이브러리( _.) 본문

TIL ⭐

lodash 라이브러리( _.)

merrytang 2022. 8. 14. 22:14

lodash란?

  • lodash란 JS의 인기있는 라이브러리 중 하나이다.
  • 주로 array, collection, date 등 데이터의 필수적인 구조를 쉽게 다룰 수 있게끔 하는데에 사용된다. 
  • JS에서 배열 안의 객체들의 값을 다룰때 유용하다. 특히 frontend 환경에서 많이 쓰인다. 
  • _ 라는 기호를 이용해서 사용하기 때문에 명칭 또한 lodash가 되었다. 

사용방법

_.(변수)

이런식으로 작성할 경우 lodash wrapper로 변수를 감싸게 되면서 해당 변수에 대한 chaining을 시작한다. 

장점

  • 브라우저에서 지원하지 않는 성능이 보장되어 있는 다양한 메소드를 가지고 있다.
  • 퍼포먼스 측면에서 native보다 더 나은 성능을 가진다.
  • npm이나 기타 패키지 매니저를 통해 쉽게 사용 가능하다. 

lodash method

array관련

_.findindex()

배열내에서 원하는 index를 구할 수 있다.

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];
 
_.findIndex(users, function(o) { return o.user == 'barney'; });
// => 0
 
// The `_.matches` iteratee shorthand.
_.findIndex(users, { 'user': 'fred', 'active': false });
// => 1
 
// The `_.matchesProperty` iteratee shorthand.
_.findIndex(users, ['active', false]);
// => 0
 
// The `_.property` iteratee shorthand.
_.findIndex(users, 'active');
// => 2

 

_.flatten()

다차원 배열 내의 요소를 출력할 수 있다.

_.flatten([1, [2, [3, [4]], 5]]);
// => [1, 2, [3, [4]], 5]

 

_.remove()

배열 내의 조건에 맞는 요소들을 제거한 후 반환해준다.

var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) {
  return n % 2 == 0;
});
 
console.log(array);
// => [1, 3]
 
console.log(evens);
// => [2, 4]

 

collection 관련

_.every()

배열 안 요소들의 값들을 비교하고 분석하는데 용이하다.

_.every([true, 1, null, 'yes'], Boolean);
// => false
 
var users = [
  { 'user': 'barney', 'age': 36, 'active': false },
  { 'user': 'fred',   'age': 40, 'active': false }
];
 
// The `_.matches` iteratee shorthand.
_.every(users, { 'user': 'barney', 'active': false });
// => false
 
// The `_.matchesProperty` iteratee shorthand.
_.every(users, ['active', false]);
// => true
 
// The `_.property` iteratee shorthand.
_.every(users, 'active');
// => false

 

_.find()

조건을 만족하는 컬렉션에서의 첫번째 요소를 찾는다.

var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];
 
_.find(users, function(o) { return o.age < 40; });
// => object for 'barney'
 
// The `_.matches` iteratee shorthand.
_.find(users, { 'age': 1, 'active': true });
// => object for 'pebbles'
 
// The `_.matchesProperty` iteratee shorthand.
_.find(users, ['active', false]);
// => object for 'fred'
 
// The `_.property` iteratee shorthand.
_.find(users, 'active');
// => object for 'barney'

 

_.filter()

특정 조건을 만족하는 모든 요소를 추출하는 메소드이다. 

var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];
 
_.filter(users, function(o) { return !o.active; });
// => objects for ['fred']
 
// The `_.matches` iteratee shorthand.
_.filter(users, { 'age': 36, 'active': true });
// => objects for ['barney']
 
// The `_.matchesProperty` iteratee shorthand.
_.filter(users, ['active', false]);
// => objects for ['fred']
 
// The `_.property` iteratee shorthand.
_.filter(users, 'active');
// => objects for ['barney']

 

_.map()

계산 결과 배열함수를 실행하고 그 결과를 배열로 반환한다. 

key값을 입력할 경우 해당 key값들만 추려서 반환한다.

function square(n) {
  return n * n;
}
 
_.map([4, 8], square);
// => [16, 64]
 
_.map({ 'a': 4, 'b': 8 }, square);
// => [16, 64] (iteration order is not guaranteed)
 
var users = [
  { 'user': 'barney' },
  { 'user': 'fred' }
];
 
// The `_.property` iteratee shorthand.
_.map(users, 'user');
// => ['barney', 'fred']

 

_.forEach()

배열의 값마다 함수를 실행시킬 때 용이하다.

_.forEach([1, 2], function(value) {
  console.log(value);
});
// => Logs `1` then `2`.
 
_.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
  console.log(key);
});

 

_.includes()

해당 collectioin에 target값이 있는지 판별해준다.

_.includes([1, 2, 3], 1);
// => true
 
_.includes([1, 2, 3], 1, 2);
// => false
 
_.includes({ 'a': 1, 'b': 2 }, 1);
// => true
 
_.includes('abcd', 'bc');
// => true

 

_.reduce()

첫번째 인자에 대해 배열 내부의 값을 통해 콜백함수를 실행시킨 후 결과값을 반환한다. 

_.reduce([1, 2], function(sum, n) {
  return sum + n;
}, 0);
// => 3
 
_.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
  (result[value] || (result[value] = [])).push(key);
  return result;
}, {});
// => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)

 

 

참고 

https://velog.io/@kysung95/%EC%A7%A4%EB%A7%89%EA%B8%80-lodash-%EC%95%8C%EA%B3%A0-%EC%93%B0%EC%9E%90

https://lodash.com/docs/4.17.15  <= 공식문서에 더 많은 메소드들이 정리되어 있습니다! 

'TIL ⭐' 카테고리의 다른 글

Local에서 default branch 명을 master에서 main 으로 설정하기  (0) 2022.12.30
JWT  (0) 2022.12.06
쿠키와 세션  (0) 2022.12.06
NestJS 설치방법  (0) 2022.08.10
커넥션 풀(Connection pooll)  (0) 2022.07.12