써치킴의 우당탕탕 개발 블로그

[JS Level up][Ch2][데이터 실습] Lodash 사용법 본문

파도파도 나오는 JavaScript

[JS Level up][Ch2][데이터 실습] Lodash 사용법

써치킴 2022. 2. 3. 01:59

https://lodash.com/docs/4.17.15 Document 확인

.uniqBy(Array, Text)

Text를 기준으로 배열의 중복 제거

.unionBy(Array1, Array2, Text)

Array1, Array2 두 개의 배열을 병합하고 Text를 기준으로 중복 제거

import _ from 'lodash'

const usersA = [
  { userId : '1', name : 'SEARCHKIM'},
  { userId : '2', name : 'Neo'}
]
const usersB = [
  { userId : '1', name : 'SEARCHKIM'},
  { userId : '3', name : 'Amy'}
]
const usersC = usersA.concat(usersB);   // 배열 병합
console.log('concat', usersC);
console.log('uniqBy', _.uniqBy(usersC,'userId'));   // userId 중복 제거 -> userId가 고유한 값만 반환

const usersD = _.unionBy(usersA, usersB, 'userId'); // 두개의 배열을 합치고 userId가 고유한 값만 반환
console.log('unionBy', usersD);

.find(Array, 검색할 객체 데이터 )

Array에서 검색할 객체 데이터에 해당되는 객체 반환

.findIndex(Array, 검색할 객체 데이터 )

Array에서 검색할 객체 데이터에 해당되는 객체 인덱스 반환

.remove(Array, 삭제할 객체 데이터 )

Array에서 객체 데이터에 해당되는 객체 삭제

import _ from 'lodash'

const users = [
  { userId : '1', name : 'SEARCHKIM'},
  { userId : '2', name : 'Neo'},
  { userId : '3', name : 'Amy'},
  { userId : '4', name : 'Evan'},
  { userId : '5', name : 'Lewis'}
]
const foundUser = _.find(users, { name : 'Amy'} );    // users에서 name이 Amy인 객체 데이터 찾기
const foundUserIndex = _.findIndex(users, { name : 'Amy' });    // users에서 name이 Amy인 객체의 인덱스번호 찾기
console.log(foundUser);
console.log(foundUserIndex);

_.remove(users, {name : 'SEARCHKIM'});    // users에서 name이 SEARCHKIM인 객체 데이터 삭제
console.log(users);

Comments