es6实现lodash常用方法用

随着es6逐渐普及以往借用lodash实现的一些方法可以用es新方法去替代了,本文总结几个常用的lodash方法用es6实现

1.数组去重

原生es5方法:

    var arr1 = ["a", "b", "c","b","a"];
    function unique(arr) {
        var newArr = [];
        for (var i = 0; i < arr.length; i++) {
            if(newArr.indexOf(arr[i]) == -1){
                newArr.push(arr[i]);
            }
        }
        return newArr;
    }
    console.log(arr1);
    console.log(unique(arr1));

在这里插入图片描述

lodash方法:

 var arr1 = ["a", "b", "c","b","a"];

    var arr2 = _.uniq(arr1);


    console.log(arr1);
    console.log(arr2);

在这里插入图片描述

es6方法1:利用Map对象和数组的filter方法

function unique(arr){
      const tem = new Map();
      return arr.filter(
         (a)=>{
          !tem.has(a)&&tem.set(a,1)
        }
      )
      return Array.from(new Set(arr))
    }
    
    console.log(unique(arr1));

es6方法2:利用Set对象和数组的Array.from方法

function unique(arr){

      return Array.from(new Set(arr))
    }
    
    console.log(unique(arr1));

es6方法3:利用Set+扩展运算符 …

   console.log(...[new Set(arr1)]);

2深层查找属性值

es5

var ownerArr = [{
        "owner": "Colin",
        "pets": [{"name": "dog1"}, {"name": "dog2"}]
    }, {
        "owner": "John",
        "pets": [{"name": "dog3"}, {"name": "dog4"}]
    }];
    var jsMap = ownerArr.map(function (owner) {
        return owner.pets[0].name;
    });
    console.log('------- jsMap -------');
    console.log(jsMap);

lodash

   var lodashMap = _.map(ownerArr, 'pets[0].name');
    console.log('------- lodashMap -------');
    console.log(lodashMap);

es6方法:数组转map

const arr = ["foo","bar","baz"];
const arrChangeMap = (arr) => new Map(arr.map( (value,key) => [key,value]));
console.log(arrChangeMap(arr));
console.log(arrChangeMap(arr).values());


你可能感兴趣的:(前端知识零碎)