Reputation: 37464
Using LoDash to map over an object:
_.map(items, (item) = > {
if (Array.isArray(item)) {
// don't include this in final object
}
return _.assign({
foo: "bar"
}, item);
});
Wondering what my best tactic is for not including an object in the returned, mapped, object if the current object is an array?
Upvotes: 1
Views: 225
Reputation: 214959
Another (and IMO a cleaner) solution is to use chaining:
results = _(items).reject(_.isArray).map(function(item) {
....
}).value()
Upvotes: 1
Reputation: 22553
This... just assign an empty object if item is an array, otherwise assign item:
_.map(items, (item) = > {
return _.assign({
foo: "bar"
}, Array.isArray(item)?{}:item);
});
Here's a little fiddle without the new anonymous function syntax: https://jsfiddle.net/xurm6vrr/1/
Upvotes: 0
Reputation: 2963
You may use reduce
which works perfectly for your case:
var items = [{a: 1}, ["asd"], {b: 2}];
var result = _.reduce(items, (res, item) => {
if (!Array.isArray(item)) {
_.assign(res, item);
}
return res;
}, {foo: "bar"});
See jsbin.
Upvotes: 1
Reputation: 57729
I would expect a map
function to always output the same keys as the input. The values maybe modified, but the keys remain the same.
There are other functions you can use to change the set of items like filter
or some kind of aggregate
or reduce
.
Upvotes: 0