lodash找到多个属性并合并结果

时间:2017-08-23 07:24:17

标签: javascript lodash

使用lodash的最新版本,我想知道如何通过多个属性查找并合并类似的对象。这是一个例子:

[
  {
    "id": "1",
    "name": "John",
    "function": "student"
  },
  {
    "id": "2",
    "name": "David",
    "function": "teacher"
  },
  {
    "id": "1",
    "name": "John",
    "function": null
  },
  {
    "id": "1",
    "name": "John",
    "function": "student"
  }
]

在这种情况下,我想获得:

[
  {
    "id": "1",
    "name": "John",
    "function": "student"
  },
  {
    "id": "2",
    "name": "David",
    "function": "teacher"
  }
]

类似的对象已被删除,并且已经合并了具有两个等于的属性(“id”和“name”)的类似对象。

任何解决方案吗?对于许多等价的物体,我想保留最深的物体。

提前谢谢! :)

1 个答案:

答案 0 :(得分:0)

您可以使用reference guide of Scipy v0.14.0

var arr = [
  {
    "id": "1",
    "name": "John",
    "function": "student"
  },
  {
    "id": "2",
    "name": "David",
    "function": "teacher"
  },
  {
    "id": "1",
    "name": "John",
    "function": null
  },
  {
    "id": "1",
    "name": "John",
    "function": "student"
  }
];

var newArr = _.uniqBy(arr, 'name');
console.log(newArr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>