lodash 常用方法整理

Lodash入门使用介绍:

安装:npm install  lodash

使用:main.js中引入

import _ from 'lodash';// 导入loadsh
Vue.prototype.$lodash = _;//注入工具

方法:

1.times()循环

        //js原生的循环方法
        for (var i = 0; i < 5; i++) {
            console.log(i);
        };
        
        //ladash的times方法
        this.$lodash.times(5,function (item) {
            console.log(item);
        })

2.map() 获取对象数组中某一同名属性的属性值集合

        let arr = [{owner: "brown",
            lovers: [{name: "cony"}, {name: "choco"}]
        }, {
            owner: "James",
            lovers: [{name: "sally"}, {name: "Jessica"}]
        }];

        //js原生的循环方法
        var jsMap = arr.map(function (item) {
            return item.lovers[0].name;
        });
        console.log(jsMap); //["cony", "sally"]


        // Lodash的写法
        var lodashMap = this.$lodash.map(arr, 'lovers[0].name');
        console.log(lodashMap); //["cony", "sally"]

3.get () 获取对象中的某个属性的值

let obj = {a: [{b: {c: 3}}]}
let c = this.$lodash.get(obj, 'a[0].b.c')  //c==3

4.cloneDeep() 深克隆对象

        let objA = {name: "brown"};

        //JS深克隆  
        JSON.parse(JSON.stringify(objA))

        // Lodash的方法
        let objB = this.$lodash.cloneDeep(objA);
        console.log(objA); //{name: "brown"}
        console.log(objB);//{name: "brown"}
        console.log(objA === objB); //false
        

5. find() 、filter()、 reject() 查找属性

find()第一个返回真值的第一个元素。
filter()返回真值的所有元素的数组。
reject()是_.filter的反向方法,返回所有假值
  let arr = [
      {owner: "brown", age:18},
      {owner: "James", age:20}
    ];
    console.log(this.$lodash.find(arr, function (item) {
        return item.age < 19;
    })); 

 

6.findIndex() 查找正确的第一个索引项

        var users = [
            { user: 'brown',  active: false },
            { user: 'cony',    active: false },
            { user: 'sally', active: true }
        ];
        this.$lodash.findIndex(users, function(chr) {
            return chr.user == 'sally';
        }); // 2

        this.$lodash.findIndex(users, { 'user': 'cony', 'active': false }); // 1
        this.$lodash.findIndex(users, 'active', false);// 0
        this.$lodash.findIndex(users, 'active'); // 2

7.asssign合并对象

8.forEach() 遍历循环

9.获取数组中指定元素 last() nth()

take()获取数组中前n个元素,不改变原数组

10.values() 把 object 自身可枚举属性的值为数组

        
        var obj = {
            a: {
                "leaf": 1
            },
            b:{
                "leaf": 2
            }
        }

        console.log(this.$lodash.values(obj)); // [{leaf: 1},{leaf: 2}]
        

 

posted @ 2021-03-31 10:56  氧化成风  阅读(978)  评论(0编辑  收藏  举报