Lodash 사용법 정리
Import
// Common JS
const _ = require('lodash')
// ES6
import * as _ from 'lodash'
오브젝트 깊은 복사(Deep Copy)
const clone = _.cloneDeep(original)
Exception없이 오브젝트의 필드 가져오기
// post, post.article, post.article.user 중 하나라도 없을 경우에
// 기본값(없을 경우 undefined) 리턴
const userName = _.get(store, 'post.article.user.name', 'Default Value')
필드값에 따른 필터링
// 오브젝트 배열에서 deleted가 false인 오브젝트들만 필터링
const filteredPosts = _.filter(posts, { deleted: false })
인덱스 검색
// 오브젝트 배열에서 id값이 'FindID'인 오브젝트를 찾아 그 인덱스를 리턴
const index = _.findIndex(posts, { id: 'FindID' })
여러 인자로 오브젝트 배열 정렬
// 먼저 'score'를 기준으로 정렬 후, 'createdAt'으로 정렬
const comments = _.sortBy(comments, ['score', 'createdAt'])
Dictionary를 Array로 변경
const dict = {
'id-1': { value: 1 },
'id-2': { value: 2 },
'id-3': { value: 3 }
}
const array = _.values(dict)
console.log(array)
// 출력값
// [ { value: 1 }, { value: 2 }, { value: 3 } ]
배열이나 오브젝트가 비어있는지 확인
const empty = _.isEmpty(obj)
오브젝트 배열에서 모든 오브젝트에 대해 특정 필드를 제거하기
const images = [
{ src: 'src-1', name: 'name-1', size: 10 },
{ src: 'src-2', name: 'name-2', size: 20 },
{ src: 'src-3', name: 'name-3', size: 30 }
]
// 모든 오브젝트들에 대해 'src' 필드를 제거
const newImages = images.map((image) => _.omit(image, 'src'))
console.log(newImages)
// 출력값
// [ { name: 'name-1', size: 10 },
// { name: 'name-2', size: 20 },
// { name: 'name-3', size: 30 } ]
오브젝트 배열을 Dictionary로 변경
const array = [
{ id: 'id-1', value: 1 },
{ id: 'id-2', value: 2 },
{ id: 'id-3', value: 3 }
]
const dict = _.keyBy(array, 'id')
console.log(dict)
// 출력값
// { 'id-1': { id: 'id-1', value: 1 },
// 'id-2': { id: 'id-2', value: 2 },
// 'id-3': { id: 'id-3', value: 3 } }