"Boldness has genius, power, and magic in it." - Johann Wolfgang von Goethe

JavaScript

[JS] JavaScript Lodash 사용법 정리

Toproot 2021. 7. 27. 21:16
728x90
728x90

 

📒 Lodash 사용법

 

 

Lodash Documentation

_(value) source Creates a lodash object which wraps value to enable implicit method chain sequences. Methods that operate on and return arrays, collections, and functions can be chained together. Methods that retrieve a single value or may return a primiti

lodash.com

 

_.uniqBy(array)

  • 중복데이터 제거.
  • concat, _.uniqBy, _unionBy
import _ from 'lodash'

const usersA = [
  { 
    userId: '1', 
    name: 'HEROPY' 
  },
  { userId: '2', name: 'Neo'}
]
const usersB = [
  { userId: '1', name: 'HEROPY' },
  { userId: '3', name: 'Amy'}
]
// concat : 배열 병합(중복데이터 발생)
const usersC = usersA.concat(usersB)
console.log('concat', usersC)

//_.uniqBy : 'userId'(속성이름)의 중복 제거 후 반환
console.log('uniqBy', _.uniqBy(usersC, 'userId'))

// _.unionBy : 두 개의 배열을 합친 후 중복제거 (한꺼번에)
const usersD = _.unionBy(usersA, usersB, 'name')
console.log('unionBy', usersD)

 

 

  • _.find , _.findIndex, _.remove
import _ from 'lodash'

// 사용자 정보
// 배열 > 객체
const users = [
  { userId: '1', name: 'HEROPY'},
  { userId: '2', name: 'Neo'},
  { 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)

_.remove(users, { name: 'HEROPY' })
console.log(users)

 

 

728x90
728x90