Reputation: 293
If I have something like
var obj = [{keywords: "a, b, c"}, {keywords: "d, e, f"}]
and do
var result = _.pluck(obj, 'keywords')
I get
result == ['a, b, c', 'd, e, f']
I'd like to have
result == ['a', 'b', 'c', 'd', 'e', 'f']
is there any simple, short way to accomplish that with underscore or lo-dash? Without iterating over result, doing a string split and putting that into a new array?
Upvotes: 0
Views: 1134
Reputation: 338316
How about
var result = _(obj).pluck('keywords').join().replace(/\s/g, '').split(',');
Edit: A shorter version, ramifications discussed in the comments:
var result = _(obj).pluck('keywords').join().split(/[\s,]+/);
Upvotes: 3
Reputation:
Without underscore:
[].concat.apply([], obj.map(function(o) { return o.keywords.split(/[,\s]+/); }))
This takes advantage of the fact that concat
does a kind of flattening, in the sense that it adds individual elements in arrays in the argument list to the result.
Upvotes: 2
Reputation: 95315
"Without iterating over result, doing a string split and putting that into a new array"?
No; any solution will wind up doing some version of that. You can, however, express that iteration/split/array construction fairly concisely:
_.flatten(_.map(obj, function(o){ return o.keywords.split(/,\s*/) }))
or if you prefer method-chaining:
_.chain(_.map(obj, function(o){ return o.keywords.split(/,\s*/) })).flatten()
but in that case, you might prefer this even more:
_(obj).map(function(o){ return o.keywords.split(/,\s*/) })).flatten()
(This is one of the cases that makes me wish Underscore/LoDash had a flatMap
; calling flatten
on the result of a regular map
destroys any deep structure.)
Upvotes: 1