lodash 에 대하여

Hyunwoo Jin·2022년 6월 3일
0

library

목록 보기
1/1

블로그 제작 중 md 파일을 읽어오는 과정에서 markdown 에디터 와
lodash 가 필요하다하여 install 하였다. 하지만 기능은 알고 써야 할 것같아서 작성하게 되었다. 누구에게 도움이 되기를 바라며..

lodash ?

lodash 는 javaScript 의 인기있는 라이브러리이다.
대게 array, collection, date 등 데이터의 필수적인 구조를 쉽게 다룰 수 있게끔 하는 데 사용된다고 한다.
javaScript에서 배열 안의 객체들의 값을 핸들링(배열, 객체 및 문자열 반복 / 복합적인 함수 생성) 할 때 유용하다고 한다.
이러한 점을 통해 JavaScript의 코드를 줄여주고, 빠른 작업에 도움이 되며 특히 프론트엔드 환경에서 많이 사용된다고 한다.
ㅡ.(변수) : lodash wrapper 로 변수를 감싸게 되어 해당 변수에 대한 chaining 을 시작한다.
_ 라는 기호를 사용하기 때문에 lodash라는 명칭이 붙게 된 것이라고 한다.

lodash를 사용 하는 이유 !

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

lodash 의 method

array 관련 method

findIndex()

형식: _.findindex(array,[predicate=.indentity],[thisArg])
출력: index number
배열 내에서 원하는 index를 쉽게 구할 수 있다.

	var myFriend = [
 {name:'kys',job:'developer',age:27},
 {name:'cys',job:'webtoons man',age:27},
 {name:'yhs',job:'florist',age:26},
 {name:'chj',job:'nonghyup man',age:27},
 {name:'ghh',job:'coffee man',age:27},
 {name:'ldh',job:'kangaroo father',age:27},
 {name:'hsy',job:'monk',age:27},
];

// 콜백함수를 통해 나이가 26인 객체가 처음으로 나오는 index 반환
_.findIndex(myFriend, function(friend) {
  return friend.age === 26;
});
// -> 2

// 처음 일치하는 object의 index 값을 반환합니다.
_.findIndex(myFriend, { name: 'cys', job:'webtoons man',age: 27 });
// -> 1

// 나이가 26인 객체가 처음으로 나오는 index 반환
_.findIndex(myFriend, age: 27);
// → 0

flatten()

형식: _.flatten(arraym[isDeep])
다차원 배열 내의 요소를 출력하는데 편리하다.

// 배열안의 배열 값을 순서대로 나열합니다.(depth를 명시하지 않을 경우1depth만)

_.flatten([1, [2, 3, [4]]]);
// → [1, 2, 3, [4]]

// 배열안의 배열 값을 깊이와 상관없이 순서대로 나열합니다.
_.flatten([1, [2, 3, [4]]], true);
// → [1, 2, 3, 4]

remove()

형식: .remove(array, [predicate=.identity], [thisArg])
출력: 제거된 array
배열 내의 조건에 맞는 요소들을 제거한 후 반환해줍니다.

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 관련 method

every()

형식: .every(collection, [predicate=.identity], [thisArg])
출력: boolean 값
배열 안 요소들의 값들을 비교하고 분석하는데 용이하다.

var myFriend = [
  { name: 'kys', active: false },
  { name: 'cys', active: false }
];

// 값을 비교할 수 있습니다.
_.every(myFriend, { name: 'kys', active: false });
// → true

// key와 value가 있는지 확인할 수 있습니다.
_.every(myFriend, 'active', false);
// → true

// key에 해당하는 value가 모두 true이면 true를 반환합니다.
_.every(myFriend, 'active');
// → false

find()

형식: .find(collection, [predicate=.identity], [thisArg])
find()는 조건을 만족하는 컬렉션에서의 첫번째 요소를 찾는 메소드입니다.

findIndex() 는 번째를 찾고 find() 는 해당 배열을 가져오는 것 같다.

var myFriend=[
 {name:'kys',job:'developer',age:27},
 {name:'cys',job:'webtoons man',age:27},
 {name:'yhs',job:'florist',age:26},
 {name:'chj',job:'nonghyup man',age:27},
 {name:'ghh',job:'coffee man',age:27},
 {name:'ldh',job:'kangaroo',age:27},
]

// 콜백함수가 처음으로 참이되는 객체를 반환
_.find(myFriend, function(friend) {
  return friend.age < 28;
});
// → { name: 'kys',job:'developer' ,'age': 27}

filter()

형식: .filter(collection, [predicate=.identity], [thisArg])
filter()는 특정 조건을 만족하는 모든 요소를 추출하는 메소드입니다.

해당 메소드를 사용해 볼 예정

webSites = [
  {
    no: 1,
    name: '웹',
    enName: 'web'
  },
  {
    no: 2,
    name: '이즈',
    enName: 'is'
  },
  {
    no: 3,
    name: '프리',
    enName: 'free'
  }
]
// enName : '이름" 에 'e' 가 들어가 있는 배열 filtering
_.filter(webSites, function(i) {
  return i.enName.indexOf('e') !== -1
});
// 출력 결과

[
  {
    enName: "web",
    name: "웹",
    no: 1
  },
  {
    enName: "free",
    name: "프리",
    no: 3
  }
]

map()

형식: .map(collection, [iteratee=.identity], [thisArg])
출력: 계산 결과 배열함수를 실행하고 그 결과를 배열로 반환합니다. key값을 입력할 경우 해당 key값들만 간추려서 반환한다.

맵..갓 너로 정했다.

function timesTwo(n) {
  return n * 3;
}

_.map([1,2],timesTwo);
//->[3,6]

var myFriend=[
  {'name':'kys'},
  {'name':'cys'},
];

.map(myFriend,'name');
//->['kys','cys']

includes()

형식: _.includes(collection, target, [fromIndex=0])
출력: boolean
해당 collection에 target 값이 있는지 판별해준다.

// 배열에 값이 있는지 찾습니다.
_.includes([1, 2, 3], 1);
// → true

// index에 해당 값이 있는지 찾습니다.
_.includes([1, 2, 3], 1, 2);
// → false

// 일치하는 값이 있는지 찾습니다.
_.includes({ 'name': 'yhs', 'age': 26 }, 'yhs');
// → true

// 일치하는 값이 문자열 안에 있는지 찾습니다.
_.includes('dontknow', 'ont');
// → true

reduce()

형식: .reduce(collection, [iteratee=.identity], [accumulator], [thisArg])

// 배열에 값이 있는지 찾습니다.
_.includes([1, 2, 3], 1);
// → true

// index에 해당 값이 있는지 찾습니다.
_.includes([1, 2, 3], 1, 2);
// → false

// 일치하는 값이 있는지 찾습니다.
_.includes({ 'name': 'yhs', 'age': 26 }, 'yhs');
// → true

// 일치하는 값이 문자열 안에 있는지 찾습니다.
_.includes('dontknow', 'ont');
// → true

forEach()

형식: .forEach(collection, [iteratee=.identity], [thisArg])
배열의 값마다 함수를 실행시킬 때 용이하게 사용됩니다.

_([1, 2]).forEach(function(n) {
  console.log(n);
}).value();
// 1
// 2

마치며..

lodash 에 대해서 간단하게 알아보았다. 생각보다 편하게 사용할 수 있고,
다양한 활용이 가능할 것 같다. 문제 해결에는 map()filter() 를 활용해 볼 예정이다.

해당 게시물은 개발자 김용성님의 블로그에서 발췌하여 인용되었습니다.
원본 링크 : "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"

profile
꾸준함과 전문성

0개의 댓글