DavidB
DavidB

Reputation: 2596

Underscore - get property from each item, group by and discard rest

I have a collection of objects and I am trying to get all property values called 'impact' from the top level, discard all other properties and child collections, group by the 'impact' and then ideally label the values with the word impact

var topics = [{
  var1 : "hi", var2 : "yo", children : [], impact : "high"
}, {
  var1 : "hi", var2 : "yo", children : [], impact : "med"
}, {
  var1 : "hi", var2 : "yo", children : [], impact : "low"
   {
  var1 : "hi", var2 : "yo", children : [], impact : "med"
},
}]

And I want [{impact: "High"}, {impact: "Low"}, {impact: "Med"}]

I have tried the following but it doesn't work

var impacts = _.chain(topics).pluck("impact").groupBy("impact").value();

Upvotes: 2

Views: 277

Answers (1)

zangw
zangw

Reputation: 48476

Try it with sortedUniqBy() and pick() and map() within Lodash.

var o = _.sortedUniqBy(product, function(e) {return e.impact;})
_.map(o, function(e) {return _.pick(e, 'impact')})

Upvotes: 3

Related Questions