07.Lodash

Updated:


Lodash 사용법

Lodash Documentation

🔑 Lodash 에서 주로 사용되는 주요 기능

1. _.uniqBy(), _.unionBy()

  • array를 병합할때, 중복되는 부분을 제거해주고 return 해주는 것입니다.(고유화 작업을 해줌)

_.uniqby(병합된 array, ‘중복 제거할 기준이 되는 값’) => 이미 중복이 발생한 데이터에 사용됩니다.

_.unionBy(선택1 array, 선택2 array, ‘중복 제거할 기준이 되는 값’) => 아직 병합하지 않은 원래 데이터, array를 대상으로 병합해서 중복된것을 제거 해줍니다.

import _ from "lodash";

const usersA = [
  { userId: "1", name: "Jacob" },
  { userId: "2", name: "Emma" },
];

const usersB = [
  { userId: "1", name: "Jacob" },
  { userId: "3", name: "John" },
];

const usersC = usersA.concat(usersB);
console.log("concat", usersC); // .concat 배열 데이터를 병합해서 새로운 array로 return
// 대신 .concat 은 단순히 중복되는 값들 이 그대로 출력됨
// 중복되는 부분을 제거 하기 위해 사용되는 method
console.log("uniqBy", _.uniqBy(usersC, "userId"));

const usersD = _.unionBy(usersA, usersB, "userId");
console.log("unionBy", usersD);

image

  • 여러 데이터를 처리할때, 중복된 data를 처리할때 유용하게 사용하는 method 입니다. (많이 사용됨..)

2. _.find(), _.findIndex()

  • 배열 데이터에서 무엇인가 찾을때 쓰는 method (value, index를 찾음)

_.find(변수명, { 검색 할 조건 }) => value return

_.findIndex(변수명, { 검색 할 조건 }) => index return

import _ from "lodash";

const users = [
  { userId: "1", name: "Jacob" },
  { userId: "2", name: "Emma" },
  { userId: "3", name: "Amy" },
  { userId: "4", name: "Evan" },
  { userId: "5", name: "Lewis" },
];
const foundUser = _.find(users, { name: "Amy" });
const foundUserIndex = _.findIndex(users, { name: "Amy" });

console.log(foundUser);
console.log(foundUserIndex);

image

3. _.remove()

  • 배열 데이터에서 무엇인가 지울때 쓰는 method

_.remove(변수명, { 검색 할 조건 }) => 선택된 조건 지우고 새로운 데이터로 return

import _ from "lodash";

const users = [
  { userId: "1", name: "Jacob" },
  { userId: "2", name: "Emma" },
  { userId: "3", name: "Amy" },
  { userId: "4", name: "Evan" },
  { userId: "5", name: "Lewis" },
];
_.remove(users, { name: "Jacob" });
console.log(users);

image

Reference

Leave a comment