NodeJS使用lodash去重排序以及比较对象数组

NodeJS使用lodash去重排序以及比较对象数组

在NodeJS中可以使用lodash对对象数据进行去重并且排序。

let option = [
    {
        "id": 1,
        "name": "aaa"
    },
    {
        "id": 1,
        "name": "aaa"
    },
    {
        "id": 3,
        "name": "ccc"
    },
    {
        "id": 3,
        "name": "ccc"
    },
    {
        "id": 5,
        "name": "eee"
    }
]

引入lodash

const lodash = require('lodash');

去重

//对内容相同的对象去重
let disArr = lodash.uniqWith(option, lodash.isEqual);

排序

//通过id字段排序,asc升序,desc降序
let sortArr = lodash.orderBy(disArr, 'id', 'desc');

//先以id升序,再以name降序
let sortArr = lodash.orderBy(disArr, ['id', 'name'], ['asc', 'desc']);

分组

//根据id分组
let group = lodash.groupBy(option, 'id');

比较对象数组

const lodash = require('lodash');

let array1 = [{id : 1, a : 'a1'}, {id : 2, a : 'a2'}];
 
let array2 = [{id : 1, a : 'a1'}];

//  _.differenceWith(array, [values], [comparator])
//  1.array (Array): 要检查的数组。
//  2.[values] (...Array): 排除的值。
//  3.[comparator] (Function): comparator 调用每个元素。
let resp = lodash.differenceWith(array1, array2, lodash.isEqual);
console.log(resp);

//输出结果:
[ { id: 2, a: 'a2' } ]

注意:
使用lodash的differenceWith()比较对象数组,若两个数组中仅仅是对象的顺序不一致,会视为这两个对象数组内容相同。


版权声明:本文为u013071014原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。