Reputation: 105
I've been having a heck of a time trying to figure this out. Still relatively new to _Underscore JS and I'm attempting to create an array of unique values from an array of nested objects. Example data below:
[
{
"property":"prop1",
"list":[
{
"description":"description blah",
"type":"F",
"values":{
"value1":30.0,
"value2":0.0
}
},
{
"description":"description blah",
"type":"F",
"values":{
"value1":30.0,
"value2":0.0
}
}
]
},
{
"property":"prop2",
"list":[
{
"description":"description blah",
"type":"Q",
"values":{
"value1":30.0,
"value2":0.0
}
}
]
}
]
What I'm attempting to get back is an array of ALL the UNIQUE nested "type" values. Example of data back below:
["F","Q"]
I've attempted _.pluck
and _.map
with little success. Would I need to utilize something different, such as chaining them? Appreciate any help I could get on this.
Upvotes: 1
Views: 594
Reputation: 27986
Here's a solution that uses chaining:
let result = _.chain(data)
.pluck('list')
.flatten()
.pluck('type')
.uniq()
.value();
This works by first plucking the lists from the data and flattening them. Then the type is plcuked from the list before finally calling uniq to get the unique types.
Upvotes: 2
Reputation: 1492
_.unique(_.flatten(_.map(myList, item => _.map(item.list, i => i.type))));
Underscore is not the greatest when it comes to composing functions since it takes data first. lodash-fp
and ramda
are much better in this regard.
Working fiddle: https://jsfiddle.net/8eLk7t15/
Upvotes: 0
Reputation: 104795
You can do this regular JS and reduce
(sorry, I'm not very familiar with underscore, so I figured I'd offer a vanilla solution for now)
var uniqueValues = data.reduce(function(vals, d) {
return vals.concat(d.list.reduce(function(listVals, l) {
if (vals.indexOf(l.type) === -1 && listVals.indexOf(l.type) === -1) {
listVals.push(l.type)
}
return listVals;
}, []))
}, [])
Demo: https://jsfiddle.net/0dsdm7Lu/
Upvotes: 0