Vue中使用Lodash
安装cnpm i -S lodash全局引入import _ from 'lodash'Vue.prototype._ = _使用对象数组排序let users = [{ user: 'a', age: 48 },{ user: 'b', age: 34 },{ user: 'a', age: 42 },{ user: 'b', age: 55 }];let c = this._.ord
·
Vue2中使用
安装
npm i -S lodash
全局引入
import _ from 'lodash'
Vue.prototype._ = _
使用
在任何地方使用_或者this._即可调用lodash
对象数组排序
let users = [
{ user: 'a', age: 48 },
{ user: 'b', age: 34 },
{ user: 'a', age: 42 },
{ user: 'b', age: 55 }
];
let c = this._.orderBy(users, ['age'], ['desc']);
console.log('age降序排列:', c);
let d = _.orderBy(users, ['user', 'age'], ['desc', 'asc']);
console.log('user降序,age升序排序:', d);
场景1:
我们要可视化今天各个小时的数据,其中x轴为
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15'],但是后端返回的json数据中缺失了某个时间段的数据,为了不让echart中时间段错位,我们需要补上这一条数据,其值设置为0
封装函数:
test(
arr1 = ['00', '01', '02', '03'],
arr2 = [
{ value: '12', name: '00' },
{ value: '45', name: '01' },
{ value: '65', name: '03' }
],
orderKey = 'name',
order = 'asc'
) {
let arr_result = arr2.map((d) => d.name);
let a = arr1.filter((item) => !arr_result.includes(item));
if (a.length !== 0) {
a.forEach((item) => {
arr2.push({ value: '0', name: item });
});
}
return _.orderBy(arr2, [orderKey], [order]);
},
下面是一个示例,说明如何根据每个对象中的嵌套属性进行排序:
const items = [
{
id: 1,
entry: 'a',
nested: { val: 5 },
},
{
id: 5,
entry: 'five',
nested: { val: 1 },
},
{
id: 3,
entry: 'three',
nested: { val: 2 },
},
{
id: 2,
entry: 'two',
nested: { val: 3 },
},
{
id: 4,
entry: 'four',
nested: { val: 4 },
},
];
const nestedValueComparator = item => _.get(item, 'nested.val');
const nestedData = _.orderBy(items, nestedValueComparator, ['asc']);
Vue3中使用
安装:
npm i -S lodash-es
引入:
import { debounce } from 'lodash-es';
使用防抖函数:
更多推荐
已为社区贡献65条内容
所有评论(0)