当前位置: 首页 > 工具软件 > lodash > 使用案例 >

Lodash

龚运乾
2023-12-01

Lodash

提供模块化、性能和额外功能的现代JavaScript实用程序库。官方地址:https://lodash.com/

数组

数组去重

  • 按数组元素去重
 const array1 = [1,1,2,3]
 const arr1 = uniqWith(array1, isEqual) // [1,2,3]

 const array2 = [
	 {id: 111, name: 'aaa'},
	 {id: 111, name: 'aaa'},
	 {id: 222, name: 'bbb'}
 ]
 const arr2 = uniqWith(array2, isEqual) // [{id: 111, name: 'aaa'}, {id: 222, name: 'bbb'}]
  • 按元素属性去重
 const array3 = [
 	{id: 1, name: 'a'},
 	{id: 2, name: 'b'},
 	{id: 1, name: 'c'}
 ]
 const arr3 = uniqBy(array3, 'id') // [{id: 1, name: 'a'}, {id: 2, name: 'b'}]

数组排序

  • 按元素排序
const array1 = [1, 5, 2, 7, 9]
const arr1 = sortBy(array1) // [1,2,5,7,9]

const array2 = [
	{eth: 'em3', data: 222222},
	{eth: 'em4', data: 111111}
]
const arr2 = sortBy(array2, ['eth']) // [{eth: 'em3', data: 222222}, {eth: 'em4', data: 111111}]
const arr3 = sortBy(array2, ['data']) // [{eth: 'em4', data: 111111}, {eth: 'em3', data: 222222}]

数组分组

const array1 = [
      { id: 111, name: 'aaa' },
      { id: 222, name: 'bbb' },
      { id: 111, name: 'ccc' }
]
console.log(groupBy(array1, 'id')) 
    // {
    //   111: [
    //     { id: 111, name: 'aaa' },
    //     { id: 111, name: 'ccc' }
    //   ],
    //   222: [{ id: 222, name: 'bbb' }]
    // }

console.log(groupBy(['one', 'two', 'three'], 'length')) // {3: ["one", "two"], 5: ["three"]}

数组元素格式化

const array = ["deviceStatus", "policyType"]
const arrayAll = [
	{ value: "deviceStatus", text: "设备状态" },
	{ value: "policyType", text: "策略类型"}
]
const arrayNew = map(array, (item) => {
	const obj = find(arrayAll, ["value", item])
	if(obj) {
		return obj.text
	}
})
console.log(arrayNew) // ["设备状态", "策略类型"]
 类似资料: