Introduction to Lodash and summary of the most commonly used methods

Keywords: Javascript Attribute Vue JSON

I. Introduction of Lodash:

Lodash is a set of tool library, which encapsulates many processing functions for common data types, such as strings, arrays, objects and so on, to help developers reduce the difficulty of using JS.

Introduction to Lodash:

Take Vue-cli as an example:

1,yarn install lodash
2. Introduce and use in main.js

import _ from 'lodash';// Import loadsh
Vue.prototype.$lodash = _;//Injection tool

3. Introduction of Lodash's common methods:
Time () cycle

        //js native loop method
        for (var i = 0; i < 5; i++) {
            console.log(i);
        };
        
        //Time method of ladash
        this.$lodash.times(5,function (item) {
            console.log(item);
        })

(2) map() obtains the set of attribute values of an attribute with the same name in the array of objects;

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

        //js native loop method
        var jsMap = arr.map(function (item) {
            return item.lovers[0].name;
        });
        console.log(jsMap); //["cony", "sally"]


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

(3) get () to get the value of an attribute in an object

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

Clone Deep () Deep Clone Object

        let objA = {name: "brown"};

        //JS deep clone  
        JSON.parse(JSON.stringify(objA))

        // Lodash's method
        let objB = this.$lodash.cloneDeep(objA);
        console.log(objA); //{name: "brown"}
        console.log(objB);//{name: "brown"}
        console.log(objA === objB); //false
        
        

_: find(), filter(), reject() find attributes

find() The first element that returns the true value.
filter() returns an array of all elements of the true value.
reject() is the reverse method of. filter, returning all false values

        console.log(this.$lodash.find(lovers, function (item) {
            return item.age < 19;
        })); //{lover: "sally", age: 18, active: true}


        console.log(this.$lodash.find(lovers, {age: 18, active: true}));
        // {lover: "sally", age: 18, active: true}


        console.log(this.$lodash.filter(lovers, {age: 18, active: true}));
        //[{lover: "sally", age: 18, active: true}]


        console.log(this.$lodash.find(lovers, ['active', false]));
        // {lover: "cony", age: 19, active: false}

        console.log(this.$lodash.filter(lovers, ['active', false]));
        // [{lover: "cony", age: 19, active: false}]
        
        console.log(this.$lodash.find(lovers, 'active'));
        // {lover: "sally", age: 18, active: true}

        console.log(this.$lodash.filter(lovers, 'active'));
        // [{lover: 'sally', age: 18, active: true},
        //  {lover: 'brown', age: 20, active: true},]
        
        

_: findIndex() Finds the correct first index item

        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

_: assign(), merge() merge
Similarities: Both can be used to merge objects and modify the original object (if the original object is the first parameter of the function);

Difference
The assign function does not deal with the attributes on the prototype chain, nor does it merge the same attributes. Instead, it overrides the previous attributes with the latter attributes.
When merge encounters the same attribute name, if the attribute value is a pure object or collection, the attribute value will be merged.

       // JS Native Object Merging
        Object.prototype.extend = function(obj) {
            for (var i in obj) {
                if (obj.hasOwnProperty(i)) {    //Determine whether the extended object has an attribute or not.
                    this[i] = obj[i];
                }
            }
        };
        var objA = {name: "brown", "food": "salmon"};
        var objB = {name: "cony", "loveEat": true};
        objA.extend(objB);
        console.log(objA); //{name: "cony", food: "salmon", loveEat: true}

        // Lodash's Way
        console.log(this.$lodash.assign(objA, objB));
        //{name: "cony", food: "salmon", loveEat: true}

        //-----------

        const aa = this.$lodash.assign({a:1},{a:2},{b:3}) //{a:2,b:3}
        const bb = this.$lodash.merge({a:1},{a:2},{b:3}) //{a:2,b:3}

        const a1 = this.$lodash.assign({},{a:1},{b:{a:1,b:2}},{b:{a:3}}) //{a:1,b:{a:3}}
        const a2 = this.$lodash.merge({},{a:1},{b:{a:1,b:2}},{b:{a:3}}) //{a:1,b:{a:3,b:2}}
        

_: forEach() traversal loop

        
        this.$lodash(['a', 'b']).forEach(function(item) {
            console.log(item);// ab
        });

        this.$lodash.forEach(['a', 'b'] , function(item, key) {
            console.log(item,key); // a 0   b 1
        });

_: Gets the last() nth() of the specified element in the array.

        //last Last last
        let arr = [1, 2, 3, 4, 5]
        let lastElement = this.$lodash.last(arr);
        console.log(lastElement); // 5
        
        //Second to last
        let lastSecondElement = this.$lodash.nth(arr,-2)
        console.log(lastSecondElement); // 4
        
        //First
        let lastSecondElement = this.$lodash.nth(arr,0)
        console.log(lastSecondElement); // 1
        
        

_: take () gets the first n elements of an array without changing the original array

        //last Last last
        let arr = [1, 2, 3, 4, 5]
        let lastElement = this.$lodash.last(arr);
        console.log(lastElement); // 5

        //Second to last
        let lastSecondElement = this.$lodash.nth(arr,-2)
        console.log(lastSecondElement); // 4

        //First
        let lastSecondElement = this.$lodash.nth(arr,0)
        console.log(lastSecondElement); // 1

Posted by rob_maguire on Mon, 14 Oct 2019 01:20:59 -0700