본문 바로가기
JS

자주 쓰이는 lodash-es 객체 문법 15가지

by memory-log 2024. 1. 1.

여기에는 lodash-es에서 자주 사용되는 객체 관련 함수의 예시 20개가 포함되어 있습니다. 이 함수들은 객체 조작, 변환 및 필터링에 유용합니다.

1. 객체에서 특정 키의 값 가져오기:

import _ from 'lodash-es';

const user = { id: 1, name: 'John', age: 25 };
const userName = _.get(user, 'name');
console.log(userName); // 'John'

2. 객체에서 여러 키의 값을 가져오기:

import _ from 'lodash-es';

const user = { id: 1, name: 'John', age: 25 };
const userSubset = _.pick(user, ['name', 'age']);
console.log(userSubset); // { name: 'John', age: 25 }

3. 객체를 배열로 변환:

import _ from 'lodash-es';

const user = { id: 1, name: 'John', age: 25 };
const userArray = _.toPairs(user);
console.log(userArray); // [['id', 1], ['name', 'John'], ['age', 25]]

4. 객체를 깊게 병합:

import _ from 'lodash-es';

const obj1 = { a: { b: { c: 1 } } };
const obj2 = { a: { b: { d: 2 } } };
const mergedObject = _.merge(obj1, obj2);
console.log(mergedObject); // { a: { b: { c: 1, d: 2 } } }

5. 객체에서 특정 키 제외하기:

import _ from 'lodash-es';

const user = { id: 1, name: 'John', age: 25 };
const userWithoutId = _.omit(user, 'id');
console.log(userWithoutId); // { name: 'John', age: 25 }

6. 객체를 깊게 비교:

import _ from 'lodash-es';

const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { a: 1, b: { c: 2 } };
const isEqual = _.isEqual(obj1, obj2);
console.log(isEqual); // true

7. 객체의 특정 키의 존재 여부 확인:

import _ from 'lodash-es';

const user = { id: 1, name: 'John', age: 25 };
const hasName = _.has(user, 'name');
console.log(hasName); // true

8. 객체의 특정 키가 빈 값인지 확인:

import _ from 'lodash-es';

const user = { id: 1, name: '', age: 25 };
const isNameEmpty = _.isEmpty(user.name);
console.log(isNameEmpty); // true

9. 객체의 특정 키를 변경:

import _ from 'lodash-es';

const user = { id: 1, name: 'John', age: 25 };
const updatedUser = _.set(user, 'age', 26);
console.log(updatedUser); // { id: 1, name: 'John', age: 26 }

10. 객체의 특정 키 존재 여부에 따라 값 설정:

import _ from 'lodash-es';

const user = { id: 1, name: 'John' };
const newUser = _.defaults(user, { age: 25 });
console.log(newUser); // { id: 1, name: 'John', age: 25 }

11. 객체의 특정 키를 기준으로 그룹화:

import _ from 'lodash-es';

const users = [
  { id: 1, name: 'John', role: 'admin' },
  { id: 2, name: 'Jane', role: 'user' },
  { id: 3, name: 'Doe', role: 'admin' },
];
const groupedByRole = _.groupBy(users, 'role');
console.log(groupedByRole);
// { 'admin': [{ id: 1, name: 'John', role: 'admin' }, { id: 3, name: 'Doe', role: 'admin' }],
//   'user': [{ id: 2, name: 'Jane', role: 'user' }] }

12. 객체의 특정 키를 기준으로 필터링:

import _ from 'lodash-es';

const users = [
  { id: 1, name: 'John', age: 25 },
  { id: 2, name: 'Jane', age: 30 },
  { id: 3, name: 'Doe', age: 25 },
];
const filteredByAge = _.filter(users, { age: 25 });
console.log(filteredByAge);
// [{ id: 1, name: 'John', age: 25 }, { id: 3, name: 'Doe', age: 25 }]

13. 객체에서 특정 키의 값에 대한 통계 계산:

import _ from 'lodash-es';

const users = [
  { id: 1, name: 'John', age: 25 },
  { id: 2, name: 'Jane', age: 30 },
  { id: 3, name: 'Doe', age: 25 },
];
const ageStats = _.countBy(users, 'age');
console.log(ageStats); // { '25': 2, '30': 1 }

14. 객체의 특정 키의 값들을 합산:

import _ from 'lodash-es';

const expenses = { rent: 1000, utilities: 500, groceries: 300 };
const totalExpenses = _.sum(Object.values(expenses));
console.log(totalExpenses); // 1800

lodash-es를 사용하여 객체 배열에서 특정 키의 값을 기준으로 정렬하는 예시를 아래에 제시합니다.

import _ from 'lodash-es';

const users = [
  { id: 1, name: 'John', age: 25 },
  { id: 2, name: 'Jane', age: 30 },
  { id: 3, name: 'Doe', age: 20 },
];

// 나이를 기준으로 오름차순 정렬
const sortedByAgeAscending = _.sortBy(users, 'age');
console.log(sortedByAgeAscending);
// [{ id: 3, name: 'Doe', age: 20 }, { id: 1, name: 'John', age: 25 }, { id: 2, name: 'Jane', age: 30 }]

// 나이를 기준으로 내림차순 정렬
const sortedByAgeDescending = _.sortBy(users, 'age').reverse();
console.log(sortedByAgeDescending);
// [{ id: 2, name: 'Jane', age: 30 }, { id: 1, name: 'John', age: 25 }, { id: 3, name: 'Doe', age: 20 }]

 

위 예시에서 _.sortBy(users, 'age')age 키를 기준으로 정렬한 새로운 배열을 반환합니다. 오름차순 정렬이 기본이며, 내림차순으로 정렬하려면 .reverse()를 사용할 수 있습니다.

 

_.sortBy를 사용하면 여러 키를 기준으로 정렬할 수도 있습니다. 아래는 나이를 기준으로 오름차순 정렬한 후, 동일한 나이의 경우 이름으로 내림차순 정렬하는 예시입니다.

const sortedByAgeAndName = _.sortBy(users, ['age', 'name']).reverse();
console.log(sortedByAgeAndName);
// [{ id: 2, name: 'Jane', age: 30 }, { id: 1, name: 'John', age: 25 }, { id: 3, name: 'Doe', age: 20 }]

 

이렇게 _.sortBy를 활용하면 객체 배열을 다양한 기준으로 정렬할 수 있습니다.

댓글