JS 개발에 많이 사용되는 javascript 라이브러리 lodash에 대해서 알아보고, 자주 사용되는 기능 몇 가지를 정리해 보았습니다.
lodash 란?
- 자바스크립트 유틸리티 라이브러리
- 유틸리티 라이브러리로 array, collection, date, number, object 등이 있으며, 데이터를 쉽게 다룰 수 있도록 지원
(예를들면, 배열 안에 중복 값을 제거하기 / object 배열 안에 특정 값만 추출하기 등..) - 특히, 자바스크립트에서 배열 안의 객체들의 값을 핸들링할때 유용
설치 & 사용법
npm install lodash
const _ = require("lodash");
자주 사용되는 기능
filter
배열 안에 요소들 중, 특정 값만 filtering하고 싶을때 사용
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
- 배열 안에 객체들의 요소 중, 특정 요소만 빼서 배열로 만들고 싶은 경우 사용
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);
});
// => Logs 'a' then 'b' (iteration order is not guaranteed).
lodash가 지원하는 기능들은 한번에 다루기 힘들만큼 많이 있습니다.
collection 관련해서 편리한 기능들을 사용하고 싶을 땐 lodash 공식 다큐먼트를 참고하여 사용하면 좋을 것 같습니다 :)
https://lodash.com/docs/4.17.15
Lodash Documentation
_(value) source Creates a lodash object which wraps value to enable implicit method chain sequences. Methods that operate on and return arrays, collections, and functions can be chained together. Methods that retrieve a single value or may return a primiti
lodash.com
감사합니다 :)
'Node.js' 카테고리의 다른 글
Node.js 동작원리 (0) | 2020.11.22 |
---|---|
Moment.js (0) | 2020.10.09 |