[英]Merge unique values to array from array of arrays
I have array like this: 我有这样的数组:
[
[
{id:1, name:'xxx'}
],
[
{id:2, name:'xxx'},
{id:1, name:'xxx'}
],
[
{id:2, name:'xxx'},
{id:1, name:'xxx'},
{id:3, name:'xxx'}
]
]
I need pick just objects with unique id and merge them into one array. 我只需要选择具有唯一ID的对象,然后将它们合并到一个数组中即可。 Each object has id
property, so I tried this: 每个对象都有id
属性,因此我尝试了以下方法:
_.(data).union().uniqBy(o => o.id).value()
but it gives me wrong result. 但这给了我错误的结果。
My required output should be like this: 我所需的输出应如下所示:
[{id:1, name:'xxx'}, {id:2, name:'xxx'}, {id:3, name:'xxx'}]
Can you help me with that? 你能帮我吗? Thanks. 谢谢。
Use _.flatten()
to merge the sub arrays into a single array and then apply _.uniqBy()
: 使用_.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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.