[JavaScript] 讓Lodash來幫你處理資料吧

itsems
itsems_frontend
Published in
5 min readJun 27, 2020

Lodash 是一個 JavaScript library,提供了很多常用的函式,可以替常常需要處理資料的我們省去很多時間,有時候也會比原生 JS 的效能還要好。

Outline:
- Install Lodash
- Basic Usage
- Examples

Install

此文撰寫為 Lodash v4.17.15

npm Lodash

$ npm i --save lodash

Basic Usage

Lodash 的 Methods 共分幾種大類:

- Array
- Collection
- Date
- Function
- Lang
- Math
- Number
- Object
- Seq
- String
- Util
- Properties
- Methods

比較常用到的是這幾種:

- Array
- Collection
- Object
- Util

以下是一個簡單的使用範例,可以把 array 空的或是錯誤的值去掉

/component.vue

result:

這邊整理了幾個網路上看到大家常用到,還有我也常用的方法:

Array Methods

_.compact(array)

把陣列裡的null、false、空值、undefined、NaN都拿掉

_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]

_.dropWhile(array, [predicate=_.identity])

回傳去除符合條件的資料後的陣列

_.join(array, [separator=','])

將陣列轉為一個以指定字元串起來的字串

_.join(['a', 'b', 'c'], '~');
// => 'a~b~c'

_.remove(array, [predicate=_.identity])

回傳條件比對結果為 true 的內容,比對的陣列會被刪除這些結果,這個 methods 會變動到陣列本身。

var array = [1, 2, 3, 4];var evens = _.remove(array, function(n) {
return n % 2 == 0;
});
console.log(array);
// => [1, 3] 陣列本身被變動了
console.log(evens);
// => [2, 4]

_.reverse(array)

反轉陣列,也會動到陣列本身。

var array = [1, 2, 3];_.reverse(array);
// => [3, 2, 1]
console.log(array);
// => [3, 2, 1]

_.uniq(array)

去除重複

_.uniq([2, 1, 2]);
// => [2, 1]

_.without(array, [values])

去掉所有包含條件的內容

_.without([2, 1, 2, 3], 1, 2);
// => [3]

Collection Methods

_.forEach(collection, [iteratee=_.identity])

// 印陣列
_.forEach([1, 2], function(value) {
console.log(value);
});
// => Logs `1` then `2`.
// 印物件
_.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
console.log(key);
});
// => Logs 'a' then 'b' 順序不可保證

_.every(collection, [predicate=_.identity])

是否全部符合條件

_.filter(collection, [predicate=_.identity])

如原生 filter

_.find(collection, [predicate=_.identity], [fromIndex=0])

遍尋元素,會回傳第一個符合條件的元素

Object Methods

_.has(object, path)

檢查物件是否有指定值

var object = { 'a': { 'b': 2 } };_.has(object, 'a');
// => true
_.has(object, 'a.b');
// => true
_.has(object, ['a', 'b']);
// => true

String Methods

_.lowerCase([string=''])

會去掉其他字元

_.lowerCase('--Foo-Bar--');
// => 'foo bar'
_.lowerCase('fooBar');
// => 'foo bar'
_.lowerCase('__FOO_BAR__');
// => 'foo bar'

_.split([string=''], separator, [limit])

_.split('a-b-c', '-', 2);
// => ['a', 'b']

_.toLower([string=''])

不會去掉其他字元

_.toLower('--Foo-Bar--');
// => '--foo-bar--'
_.toLower('fooBar');
// => 'foobar'
_.toLower('__FOO_BAR__');
// => '__foo_bar__'

這次的 Lodash 就分享到這邊,歡迎留言讓我知道還有什麼方法也是你喜歡也推薦的!

內容若有任何錯誤,歡迎留言交流指教! 🐬

--

--

itsems
itsems_frontend

Stay Close to Anything that Makes You Glad You are Alive.