首页 > 解决方案 > JS - 使用 lodash 删除数组中的重复对象

问题描述

例如我有这个数组:

0: {myfield: "1f974a20-aa59-11e8-9653-ab3419ed3bc9", order: 0, value: ""}
1: {myfield: "1f974a20-aa59-11e8-9666-ab3419ed3bc9", order: 0, value: ""}
2: {myfield: "1f974a20-aa59-11e8-9653-ab3419ed3bc9", order: 0, value: "One"}
3: {myfield: "af7401a0-aa6e-11e8-9653-ab3419ed3bc9", order: 1, value: "Two"}

我希望能够遍历它并弹出/删除旧版本的重复数组,在此示例中,我想保留对象 2并弹出/删除对象 0,因为它们都具有完全相同的 myfield

是否可以使用 lodash 做到这一点?

标签: javascriptreactjsloops

解决方案


您可以使用_.uniqBy()

let arr = [ {myfield: "1f974a20-aa59-11e8-9653-ab3419ed3bc9", order: 0, value: ""}, {myfield: "1f974a20-aa59-11e8-9666-ab3419ed3bc9", order: 0, value: ""}, {myfield: "1f974a20-aa59-11e8-9653-ab3419ed3bc9", order: 0, value: "One"}, {myfield: "af7401a0-aa6e-11e8-9653-ab3419ed3bc9", order: 1, value: "Two"}];

let result = _.uniqBy(arr, 'myfield');

推荐阅读