lodash
lodash는 JavaScript의 인기있는 라이브러리 중 하나입니다.
Javascript에서 배열 안의 객체들의 값을 핸들링(배열, 객체 및 문자열반복 / 복합적인 함수생성) 할 때 유용합니다.
Javascript의 코드를 줄여주고, 빠른작업에 도움이 됩니다.
- _. (변수) lodash wrapper로 변수를 감싸게 되면서 해당 변수에 대한 chaining를 시작합니다.
- _ 라는 기호를 이용해서 사용하기 때문에 명칭 또한 lodash가 된 것 입니다.
- 브라우저에서 지원하지 않는 성능이 보장되어있는 다양한 메서드를 가지고 있습니다.
- npm이나 기타패키지 매니저를 통해 쉽게 사용이 가능합니다.
# lodash method
array 관련
형식 : _.findIndex(array,[predicate=.indentity],[thisArg])
출력: index number
배열 내에서 원하는 index를 쉽게 구할 수 있다.
let result = [];
menuData = [
{name: 'red', id: 'developer'},
{name: 'orange', id: 'java'},
{name: 'blue', id: 'html'}
];
// usePages배열을 순회하면서 콜백함수를 통해 id와 pageNm이 같은 객체가 처음으로 나오는 index 반환
usePages.forEach((pageNm)=>{
let idx = _.findIndex(this.menuData, (o)=>{
return o.id === pageNm
})
// idx가 있다면 result배열에 menuData[idx]배열을 push한다.
if(idx >= 0){
result.push(this.menuData[idx])
}
})
- _.flatten
- _.flattenDeep
- _.flattenDepth
형식 : _.flatten(array, [isDeep])
입력: 다차원 배열내의 요소를 출력하는데 편리하다.
출력: 결과array
// 배열안의 배열 값을 순서대로 나열합니다.(1depth만)
console.log(_.flatten([1, 2, [3, [4]]]));
// → [1, 2, 3, [4]]
// 배열안의 배열 값을 깊이와 상관없이 순서대로 나열합니다.
console.log(_.flattenDeep([1, [2, 3, [4]]]));
// → [1, 2, 3, 4]
// 배열안의 배열 값을 depth값에 따라 순서대로 나열합니다.
console.log(_.flattenDepth([1, [2, 3, [4]]], 1));
// → [1, 2, 3, [4]]
형식: _.remove(array, [predicate=.identity], [thisArg])
출력: 제거된 array
배열 내의 조건에 맞는 요소들을 제거한 후 반환해준다.
let array = [1,2,3,4];
let result = _.remove(array, n => {
return n % 2 === 0;
});
console.log(array);
// [1,3]
console.log(result);
// [2,4]
형식: _.concat(array, [value]);
인자로 주어진 배열들을 기존 배열에 합쳐서 새배열을 반환한다.
기존값은 변하지 않음
let array = [1];
let result = _.concat(array, 2, [3], [[4]]);
console.log(array); // [1]
console.log(result); // [1, 2, 3, [4]]
// 문자열 합치기
let str = '오잉';
let newStr = str.concat('끼야', 4);
console.log(str); // '오잉'
console.log(newStr); //'오잉끼야4'
Collection 관련
형식 : .filter(collection, [predicate=.identity], [thisArg])
입력: collection
출력: 일치하는 값들의 배열
특정 조건을 만족하는 모든 요소를 추출하는 메소드이다.
let 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},
]
let result = _.filter(myFriend, {age: 26, job: 'florist'})
console.log(result);
//[{age: 26,job: "florist",name: "yhs"}]
console.log(_.filter(myFriend, obj=>obj.age===26));
//[{age: 26,job: "florist",name: "yhs"}]
형식: .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']
형식: .reduce(collection, [iteratee=.identity], [accumulator], [thisArg])
// 첫번째 인자에 대해 배열내부의 값을 통해 콜백함수를 실행시킨 후 결과값을 반환한다.
_.reduce([1, 2], function(total, n) {
return total + n;
});
// → 3
let res = _.reduce([1,2], (total, n) => {
return total + n;
})
console.log(res);
// → 3