记录lodash的方法

77 阅读1分钟

当我们用架手架创建vue项目的时候 lodash其实已经在安装好了 所以我们就不需要再安装lodash了 直接引入就可以了

引入 lodash

import _ from 'lodash'

CDN引入

<script src="cdn.bootcdn.net/ajax/libs/l…

节流的方法

joint:_.throttle(function(){ //会少量触发 用于快速滑动 },50),

防抖的方法

tremble:_.debounce(function(){ //最后一个执行 连续快速触发只会触发一次 用于input搜索 },1000)

数组的方法

演示 let arr = [ { "id": "1", "title": "事件_1", "label": "金融", "type": "企业", }, { "id": "2", "title": "事件_2", "label": "娱乐", "type": "", }, { "id": "3", "title": "事件_3", "label": "娱乐", "type": "娱乐", }, { "id": "4", "title": "事件_4", "label": "社会", "type": null, }, { "id": "5", "title": "事件_5", "label": "", "type": "社会", } ]

_.groupBy(arr, "label")

//{金融: Array(1), 娱乐: Array(2), 社会: Array(1), "": Array(1)}

import _ from 'lodash'

let output = _.groupBy(thatis.branchList, (n) => { // 对多个值进行分组 return n.label }) console.log(output);

二 数组分组的方法

_.zip(['fred', 'barney'], [30, 40], [true, false]);

// => [['fred', 30, true], ['barney', 40, false]]、

三 数组去重

_.uniq([2, 1, 2]);

// => [2, 1]

四 数组过滤假值 例如false, null,0, “”, undefined, 和 NaN 都是被认为是“假值”。

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

// => [1, 2, 3]

五 移除数组对象中指定元素 会改变原数组

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]

六 数组对象合并去重

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];

var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];

_.unionWith(objects, others, _.isEqual);

// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]

七 数组排序

let result = _.sortBy(features,function(item){ return item.code;//根据code对数据进行升序排序,如果降序则改为:return -item.code }); console.log("排序",result);