js lodash代替迭代数据结构运算

const _ = require('lodash')

  1. lodash.each
_([1, 2]).forEach(function(value) {
  console.log(value);
});
//  `1` 
// `2`.
 
_.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
  console.log(key);
});

  1. assign merge
const aa = _.assign({},{a:1},{a:2},{b:3})
//{a:2,b:3}
const bb = _.merge({},{a:1},{a:2},{b:3})
//{a:2,b:3}
const a1 = _.assign({},{a:1},{b:{a:1,b:2}},{b:{a:3}})
//{a:1,b:{a:3}}

const a2 = _.merge({},{a:1},{b:{a:1,b:2}},{b:{a:3}})
//{a:1,b:{a:3,b:2}}

  1. mergeWith
const object = { 'a': [3], 'b': [5] };
const other = { 'a': [6], 'b': [7] };
function foo (a,b) {
    if (_.isArray(a)) {
        return a.concat(b)
    }
}
function foo5 (a,b) {
    return _.toNumber(a) + _.toNumber(b)
}
const a3 = _.merge(object,other)
//{'a':[6],'b':[7]}
const a4 = _.mergeWith(object,other)
//{'a':[6],'b':[7]}
const a5 = _.mergeWith(object,other,foo)
//{'a':[3,6],'b':[5,7]}
const aaa = _.mergeWith(object,other,foo5)
//{'a':9,'b':12}

  1. sumBy
const arrs = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
const a6 = _.sumBy(arrs, k => k.n)  //20
const aa6 = _.sumBy(arrs,'n')  //20
// console.log(aa6);

const ccc = _.sum([3,16,15,20])
// console.log(ccc);

  1. sortBy
const users = [
    { 'user': 'barney',  'age': 36 },
    { 'user': 'fred',    'age': 40 },
    { 'user': 'pebbles', 'age': 1 }
  ];

  const youngest = _
  .chain(users)                         
  .sortBy('age')
  .value()
  console.log(youngest);    
//[ { user: 'pebbles', age: 1 },
// { user: 'barney', age: 36 },
// { user: 'fred', age: 40 } ]

// _.chain(arr)
//   LodashWrapper {
//     __wrapped__:   [ { user: 'barney', age: 36 },
//        { user: 'fred', age: 40 },
//        { user: 'pebbles', age: 1 } ],
//     __actions__: [],
//     __chain__: true,
//     __index__: 0,  __values__: undefined }
  const a7 = _.sortBy(users,'age')

  1. flatten
  const arr = [1,2,[3,4,[5],6]]
  const a8 = _.flatten(arr)  //[ 1, 2, 3, 4, [ 5 ], 6 ]
  const a9 = _.flattenDeep(arr)  //[ 1, 2, 3, 4, 5, 6 ]
  const a10 = _.flattenDepth(arr,2)  //[ 1, 2, 3, 4, 5, 6 ]

  1. 数组去重
  const arr2 = [12,14,11,12,12,1,14,16,17,22,2,11,12]
  const a11 = Array.from(new Set(arr2))
  const a12 = [...new Set(arr2)]
  const a13 = _.uniq(arr2)  //[ 12, 14, 11, 1, 16, 17, 22, 2 ]
  const arrObj = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 },{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
  const a14 = _.uniqWith(arrObj, _.isEqual)  //[ { x: 1, y: 2 }, { x: 2, y: 1 } ]

  1. isEqual
const object = { 'a': 1, 'b':2};
const other = { 'a': 1,'b':2 };
const a15 = _.isEqual(object, other);  //true
const a16 = _.isEqual([1,[2],2],[1,[2],2])  //true

  1. 其他
const a17 = _.random(1, 5,true);
// console.log(a17);
const a18 = _.inRange(5,1,10)  //true

const a19 = _.clamp(90, 5, 100)  //90

const a20 = _.min([14,12,11,15,14,22,10,34,12])  //10

const objects = [{ 'n': 4 }, { 'n': 2 },{'n':5},{'n':3}];

const a21 = _.minBy(objects,'n')  //{ n: 2 }   
// _.maxBy()
const a22 = _.minBy(objects,o => o.n)  //{ n: 2 }
console.log(a22);

  1. 深拷贝
_.cloneDeep()
const original = { foo: "bar" };
const newObj = _.cloneDeep(original)
original.foo = 'aaa'
console.log(original);  //{ foo: 'aaa' }
console.log(newObj);  //{ foo: 'bar' }

  1. 浅拷贝
_.clone()
const original1 = { foo: "bar" };
const newObj1 = _.clone(original)
original1.foo = 'aaa'
console.log(original1);  //{ foo: 'aaa' }
console.log(newObj1);  //{ foo: 'aaa' }

  1. reduce
const users = [
    { name: "John", age: 30 },
    { name: "Jane", age: 28 },
    { name: "Bill", age: 65 },
    { name: "Emily", age: 17 },
    { name: "Jack", age: 30 }
]
const finalRes = _.reduce(users,(result,user) => {
    if (user.age > 17 && user.age< 66) {
        (result[user.age] || (result[user.age] = [])).push(user)
    }
    return result
},{})
// { '28': [ { name: 'Jane', age: 28 }],
//   '30': [ { name: 'John', age: 30 }, { name: 'Jack', age: 30 } ], 
//   '65': [ { name: 'Bill', age: 65 }] 
// }

  1. 返回一个新的联合数组。去重
const b1 = _.union([1],[1,2],[1,2,3],[3,6,9])  //[ 1, 2, 3, 6, 9 ] 
const bb2 = _.union([1,2,3,1,2,1,11,2,3])  //[ 1, 2, 3, 11 ]
const b2 = _.unionBy([2.1], [1.2, 2.3,2.4,3.1], Math.floor);  //[ 2.1, 1.2, 3.1 ]
const b3 = _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 },{'x':3}],[{'x':2}] ,'x');
//[ { x: 1 }, { x: 2 }, { x: 3 } ]
const b4 = _.unionBy([{'x':1},{'x':2},{'x':3},{'x':3},{'x':1}],'x')
//[ { x: 1 }, { x: 2 }, { x: 3 } ]
const b5 = _.unionBy([{'x':1},{'x':2},{'x':3},{'x':3},{'x':1}],a=> a.x)
//[ { x: 1 }, { x: 2 }, { x: 3 } ]
const b6 = _.uniq([1],[1,2],[1,2,3],[3,6,9])  //1
const b7 = _.uniq([1,2,3,1,2,1,11,2,3])  //[ 1, 2, 3, 11 ]
const b8 = _.uniqBy([{ 'x': 2 }, { 'x': 1 },{'x':3},{'x':1},{'x':2}],'x')
//[ { x: 2 }, { x: 1 }, { x: 3 } ]

总结:union和uniq的区别:union支持多个数组去重,uniq只能是一个数组

  1. fromPairstoPairs
const b9 = _.fromPairs([['fred', 30], ['barney', 'a'],['some',1],['a','c']]);
//{ fred: 30, barney: 'a', some: 1, a: 'c' }
const b10 = _.toPairs({fred: 30, barney: 'a', some: 1, a: 'c' })
const b11 = Object.entries({fred: 30, barney: 'a', some: 1, a: 'c' })
//[ [ 'fred', 30 ], [ 'barney', 'a' ], [ 'some', 1 ], [ 'a', 'c' ] ]

  1. mapValues
const users = {
    'fred':    { 'user': 'fred',    'age': 40 },
    'pebbles': { 'user': 'pebbles', 'age': 1 }
  };
const c1 = _.mapValues(users,'age')  //{ fred: 40, pebbles: 1 }

16 pickBy

const object = { 'a': 1, 'b': '2', 'c': 3 };
const c2 = _.pick(object,['a','c'])  //{ a: 1, c: 3 }
const c3 = _.pickBy(object, _.isString)  //{ b: '2' }
console.log(c3);

  1. drop
const c3 = _.drop([1, 2, 3], 2);  //[ 3 ]
console.log(c3);

  1. shuffle()
const c4 = _.shuffle([1,5,11,4,3,6])   //[ 1, 11, 6, 5, 3, 4 ]  [ 4, 6, 1, 3, 11, 5 ]
const c5 = _.shuffle([['fred', 30], ['barney', 'a'],['some',1],['a','c']])  
//[ [ 'some', 1 ], [ 'a', 'c' ], [ 'barney', 'a' ], [ 'fred', 30 ] ]
const c6 = _.shuffle([{ 'user': 'fred'},{'age': 40 },{ 'user': 'pebbles'}])
//[ { user: 'pebbles' }, { age: 40 }, { user:'fred' } ]
console.log(c6);

  1. sample
const ccc = _.sample(["lisong", "heyan",'A','C'], 1);
console.log(ccc);  //heyan

  1. map
let ownerArr = [
    {
        "owner": "Colin",
        "pets": [{"name":"dog1"}, {"name": "dog2"}]
    }, 
    {
        "owner": "John",
        "pets": [{"name":"dog3"}, {"name": "dog4"}]
    }];
console.log(_.map(ownerArr, 'pets[1].name')); // 循环找寻深度数组的值 [ 'dog2', 'dog4' ]
console.log(_.map(ownerArr,o=>o.pets[1].name))  // [ 'dog2', 'dog4' ]

const users = [
    { 'user': 'barney' },
    { 'user': 'fred' }
  ];

 const c7 =  _.map(users, 'user');  //[ 'barney', 'fred' ]
 const c8 = _.map(users,o=>o.user)  //[ 'barney', 'fred' ]

  1. uniqueId
  const c9= _.uniqueId('userId')  //userId1
  const c10 = _.uniqueId('userId') //userId2
  const c11 = _.uniqueId('userId') //userId3
  1. findfilter
let F = [
    {id: 0, name: "aaa", age: 33},
    {id: 1, name: "bbb", age: 25},
    {id: 2, name: "ccc", age: 25}
];
const sss = _.find(F, ["id", _.max(_.map(F, "id"))]); //json字符串中某一项最大的
// console.log(sss);  // { id: 2, name: 'ccc', age: 25 }
const ss1 = _.find(F, ["id", 2]) // { id: 2, name: 'ccc', age: 25 }
// console.log(ss1);
const ss2 = _.filter(F, ["id", 2])  // [ { id: 2, name: 'ccc', age: 25 } ] 返回一个新的过滤后的数组。
const ss3 = _.filter(F, ["id", _.max(_.map(F, "id"))])  // [ { id: 2, name: 'ccc', age: 25 } ]

const d11 = Array.prototype.slice.apply(["a","b"]);       
console.log(d11);

// Array.prototype.slice.call(arguments)
const d13  = new Array(3)
console.log(d13);

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


  1. _.groupBy()
    image

将上图转换成下图这种数据格式:

image
const courseGroup = _.groupBy(arr, 'lesson.courseSession.objectId')
或
const courseGroup = _.groupBy(arr, e => {
  return e.lesson.courseSession.objectId
)

image
  1. Object.values()
const finalData = Object.values(courseGroup)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,406评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,732评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,711评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,380评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,432评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,301评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,145评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,008评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,443评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,649评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,795评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,501评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,119评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,731评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,865评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,899评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,724评论 2 354