我有这样的数组:
[
[
{id:1, name:'xxx'}
],
[
{id:2, name:'xxx'},
{id:1, name:'xxx'}
],
[
{id:2, name:'xxx'},
{id:1, name:'xxx'},
{id:3, name:'xxx'}
]
]
我需要选择具有唯一ID的对象并将它们合并到一个数组中。每个对象都有id
属性,所以我尝试了这个:
_.(data).union().uniqBy(o => o.id).value()
但它给了我错误的结果。
我要求的输出应该是这样的:
[{id:1, name:'xxx'}, {id:2, name:'xxx'}, {id:3, name:'xxx'}]
你可以帮帮我吗?感谢。
答案 0 :(得分:1)
使用_.flatten()
将子数组合并为一个数组,然后应用_.uniqBy()
:
const data = [[{"id":1,"name":"xxx"}],[{"id":2,"name":"xxx"},{"id":1,"name":"xxx"}],[{"id":2,"name":"xxx"},{"id":1,"name":"xxx"},{"id":3,"name":"xxx"}]];
const result = _(data)
.flatten()
.uniqBy('id')
.value();
console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
&#13;