Reputation: 7601
I'm using the following Lodash chained utilities to map/flat and array and produce a new one while excluding the undefined valued.
const array = _(resp.data)
.omit(_.isUndefined)
.flatMap('building')
.value()
console.log(array)
And this is the result:
As you can see the undefined values are still being included. Why is this?
EDIT:
resp.data looks like this
[
{ username: '', building: [ name: '' ] }
{ username: '', building: [ name: '' ] }
// etc...
]
EDIT2:
Those undefined
values are probably the empty building
that come objects have.
Upvotes: 1
Views: 321
Reputation: 30098
The extra undefined
value should belong to a user
in the resp.data
where no building
exist. All you have to do is to _.filter()
all values that are undefined
through _.identity()
after the _.flatMap()
.
Note: Using _.omit
should only be used against objects, using this in the context of an array (e.g. _.flatMap()
which results in an array) would yield a result of an object wherein the index of each item is it's index in the array. You should use _.filter()
instead.
var data = [
{ username: 'user1', building: [ { name: 'building1' } ] },
{ username: 'user2', building: [ { name: 'building2' } ] },
{ username: 'user3' }
];
var result = _(data)
.flatMap('building')
.filter(_.identity)
.value();
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js"></script>
Upvotes: 2
Reputation: 159
Try this.
const array = _(resp.data)
.omit(_.isUndefined)
.flatMap('building')
.map()
.omit(_.isUndefined)
.value()
Upvotes: 1