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. Each object has id
property, so I tried this:
_.(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()
:
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.