Lodash는 자바스크립트에서 데이터(배열/객체) 다루는 작업을 깔끔하게 만들어주는 유틸리티 라이브러리입니다. 특히 “안전한 객체 접근”, “배열 가공”, “깊은 복사/병합”, “디바운스/쓰로틀” 같은 실무 패턴에서 체감이 큽니다.
0) 설치 & 임포트 팁 (번들 크기 줄이기)
가능하면 필요한 함수만 가져오기(트리 셰이킹/번들 최적화)에 유리합니다.
// ✅ 권장: 필요한 함수만 import
import get from "lodash/get";
import debounce from "lodash/debounce";
// 또는
import { uniqBy, groupBy } from "lodash";
1) _.get — 중첩 객체 “안전하게” 접근하기
중첩된 값에 접근할 때 ?.를 써도 되지만, 기본값(default) 처리까지 간단하게 하려면 get이 편합니다.
import get from "lodash/get";
const user = {
profile: {
name: "Julie",
contact: { email: "julie@example.com" },
},
};
const email = get(user, "profile.contact.email", "no-email");
const phone = get(user, "profile.contact.phone", "no-phone");
console.log(email); // "julie@example.com"
console.log(phone); // "no-phone"
2) _.set — 중첩 객체 값 설정하기
깊은 경로에 값을 넣을 때, 중간 객체가 없으면 직접 만들기 번거롭죠. set은 경로를 따라 자동으로 만들어줍니다.
import set from "lodash/set";
const state = {};
set(state, "auth.user.profile.name", "Julie");
console.log(state);
// { auth: { user: { profile: { name: "Julie" } } } }
3) _.pick / _.omit — 필요한 필드만 추리기 / 제외하기
API 응답에서 특정 필드만 남기거나 민감정보를 제거할 때 많이 씁니다.
import pick from "lodash/pick";
import omit from "lodash/omit";
const user = {
id: 1,
name: "Julie",
email: "julie@example.com",
password: "secret",
role: "admin",
};
const publicUser = omit(user, ["password"]);
const miniUser = pick(user, ["id", "name"]);
console.log(publicUser); // password 제거
console.log(miniUser); // { id: 1, name: "Julie" }
4) _.cloneDeep — 깊은 복사(Deep Copy)
스프레드({...obj})는 얕은 복사라서 중첩 구조가 있으면 참조가 공유됩니다. 안전하게 복제하려면 cloneDeep.
import cloneDeep from "lodash/cloneDeep";
const original = { a: 1, nested: { b: 2 } };
const copied = cloneDeep(original);
copied.nested.b = 999;
console.log(original.nested.b); // 2 (✅ 영향 없음)
console.log(copied.nested.b); // 999
5) _.merge — 객체 “깊은 병합” (기본 설정 + 사용자 설정 합치기)
Object.assign은 얕게 합치지만, merge는 중첩 객체까지 자연스럽게 병합합니다.
import merge from "lodash/merge";
const defaultConfig = {
theme: { color: "blue", fontSize: 14 },
feature: { a: true, b: false },
};
const userConfig = {
theme: { fontSize: 16 },
feature: { b: true },
};
const config = merge({}, defaultConfig, userConfig);
console.log(config);
// {
// theme: { color: "blue", fontSize: 16 },
// feature: { a: true, b: true }
// }
팁: merge({}, ...)처럼 빈 객체를 첫 인자로 넣으면 원본 변경을 피할 수 있어요.
6) _.uniqBy — 특정 키 기준으로 중복 제거
리스트에서 id 기준 중복 제거는 실무에서 정말 자주 나옵니다.
import uniqBy from "lodash/uniqBy";
const items = [
{ id: 1, name: "A" },
{ id: 1, name: "A-dup" },
{ id: 2, name: "B" },
];
const unique = uniqBy(items, "id");
console.log(unique);
// [{id:1, name:"A"}, {id:2, name:"B"}]
7) _.groupBy — 그룹핑(카테고리별 묶기)
import groupBy from "lodash/groupBy";
const posts = [
{ id: 1, category: "news", title: "A" },
{ id: 2, category: "dev", title: "B" },
{ id: 3, category: "news", title: "C" },
];
const grouped = groupBy(posts, "category");
console.log(grouped);
// { news: [..], dev: [..] }
8) _.sortBy — 안전한 정렬(여러 기준도 가능)
import sortBy from "lodash/sortBy";
const users = [
{ name: "Julie", age: 32 },
{ name: "Min", age: 28 },
{ name: "Alex", age: 28 },
];
// age 오름차순, name 오름차순
const sorted = sortBy(users, ["age", "name"]);
console.log(sorted);
9) _.chunk — 배열을 N개씩 자르기 (페이지/그리드 UI에 유용)
import chunk from "lodash/chunk";
const arr = [1,2,3,4,5,6,7];
console.log(chunk(arr, 3));
// [[1,2,3],[4,5,6],[7]]
10) _.flattenDeep — 중첩 배열 평탄화
import flattenDeep from "lodash/flattenDeep";
const nested = [1, [2, [3, [4]]]];
console.log(flattenDeep(nested)); // [1,2,3,4]
11) _.sumBy — 객체 배열 합계 (가격/수량 합산에 딱)
import sumBy from "lodash/sumBy";
const cart = [
{ name: "A", price: 1200, qty: 2 },
{ name: "B", price: 500, qty: 1 },
];
const total = sumBy(cart, (item) => item.price * item.qty);
console.log(total); // 2900
12) _.debounce / _.throttle — 이벤트 최적화(검색/스크롤)
debounce: “입력이 멈춘 뒤” 실행 (검색 자동완성에 흔함)
import debounce from "lodash/debounce";
const search = (q) => console.log("API call:", q);
const onChange = debounce((e) => {
search(e.target.value);
}, 300);
// input.addEventListener("input", onChange);
throttle: “일정 주기마다” 실행 (스크롤/리사이즈에 흔함)
import throttle from "lodash/throttle";
const onScroll = throttle(() => {
console.log("scroll handler");
}, 200);
// window.addEventListener("scroll", onScroll);
13) _.isEqual — 깊은 비교(Deep Compare)
객체/배열의 “내용이 같은지” 비교할 때 ===로는 불가능합니다.
import isEqual from "lodash/isEqual";
const a = { x: 1, y: { z: 2 } };
const b = { x: 1, y: { z: 2 } };
console.log(a === b); // false
console.log(isEqual(a, b)); // true
14) _.filter — 조건에 맞는 “여러 개” 추출
✔️ 언제 쓰나
- 조건에 맞는 요소를 모두 가져올 때
- 결과는 항상 배열
import filter from "lodash/filter";
const users = [
{ id: 1, name: "Julie", active: true },
{ id: 2, name: "Min", active: false },
{ id: 3, name: "Alex", active: true },
];
const activeUsers = filter(users, (u) => u.active);
console.log(activeUsers);
// [
// { id: 1, name: "Julie", active: true },
// { id: 3, name: "Alex", active: true }
// ]
✔️ Lodash 축약 문법 (실무에서 많이 씀)
const activeUsers = filter(users, { active: true });
👉 predicate 함수를 안 써도 돼서 코드가 매우 간결합니다.
15) _.reject — 조건에 맞는 것 “제외”
✔️ 언제 쓰나
- filter의 반대 개념
- 조건에 맞는 것을 버리고 나머지 반환
- 결과는 배열
✔️ 기본 예제
import reject from "lodash/reject";
const users = [
{ id: 1, name: "Julie", active: true },
{ id: 2, name: "Min", active: false },
{ id: 3, name: "Alex", active: true },
];
const inactiveRemoved = reject(users, (u) => !u.active);
console.log(inactiveRemoved);
// active가 true인 사용자만 남음
✔️ 실무에서 자주 쓰는 패턴
예: 삭제된 항목 제거
const posts = [
{ id: 1, deleted: false },
{ id: 2, deleted: true },
{ id: 3, deleted: false },
];
const visiblePosts = reject(posts, { deleted: true });
👉 “~인 것 빼고” 라는 요구사항에 매우 직관적입니다.
16) _.find — 조건에 맞는 “첫 번째 하나” 찾기
✔️ 언제 쓰나
- 조건 만족하는 단 하나의 요소
- 결과는 객체 또는 undefined
- filter와 가장 많이 헷갈림 ⚠️
✔️ 기본 예제
import find from "lodash/find";
const users = [
{ id: 1, name: "Julie" },
{ id: 2, name: "Min" },
{ id: 3, name: "Alex" },
];
const user = find(users, (u) => u.id === 2);
console.log(user);
// { id: 2, name: "Min" }
✔️ 축약 문법 (강력함)
const user = find(users, { id: 2 });
🚨 filter vs find vs reject 한눈에 비교
| filter | 배열 | 조건에 맞는 것 모두 | “골라 담기” |
| reject | 배열 | 조건에 맞는 것 제외 | “빼고 담기” |
| find | 단일 객체 | 첫 번째 하나 찾기 | “하나만 찾기” |
✅ 실무 통합 예제 (API 응답 가공)
import filter from "lodash/filter";
import reject from "lodash/reject";
import find from "lodash/find";
const users = [
{ id: 1, name: "Julie", active: true, deleted: false },
{ id: 2, name: "Min", active: false, deleted: false },
{ id: 3, name: "Alex", active: true, deleted: true },
];
// 1️⃣ 활성 사용자 목록
const activeUsers = filter(users, { active: true });
// 2️⃣ 삭제되지 않은 사용자
const validUsers = reject(users, { deleted: true });
// 3️⃣ 특정 사용자 1명 찾기
const julie = find(users, { name: "Julie" });
console.log(activeUsers);
console.log(validUsers);
console.log(julie);
🔥 실무에서 진짜 중요한 팁
❗ 네이티브 JS와 비교
사실 modern JS에서도 가능합니다:
// native
users.filter(u => u.active);
users.find(u => u.id === 2);
하지만 Lodash가 여전히 좋은 이유:
- 객체 매칭 축약 문법
- null-safe 처리
- 일관된 함수형 스타일
- 레거시/대규모 프로젝트에서 가독성
마무리
filter, reject, find만 정확히 구분해도
👉 배열 처리 코드의 70%는 깔끔하게 정리됩니다.
특히 기억하세요:
- 여러 개 → filter (콜렉션, 조건) : 콜렉션에서 조건에 맞는 데이터만 추출
- 제외 → reject (콜렉션, 조건) : filter 와 반대
- 하나 → find (콜렉션, 조건) : 콜렉션에서 조건에 맞는 원소 반환
'IT · 프로그래밍' 카테고리의 다른 글
| 현재시간에서 5분전 구하기 (1) | 2024.09.20 |
|---|---|
| 정규식 소수점 2자리까지 되는 정수 (0) | 2023.12.13 |
| 자바에서 프로시저 호출 (0) | 2023.11.28 |
| PLAN_TABLE생성 (1) | 2023.11.28 |
| ORDER BY 1 2 (0) | 2023.11.28 |