I have a given array of objects something like:
var items = [
{item: [{foo: 21, bar: 'a' }, {foo: 5,bar: 'e'},{foo: 167, bar: 'c'}]},
{item: [{foo: 42, bar: 'a' }, {foo: 45,bar: 'd'},{foo: 7, bar: 'c'}]},
{item: [{foo: 99, bar: 'b' }, {foo: 35,bar: 'c'},{foo: 22, bar: 'e'}]},
{item: [{foo: 31, bar: 'e' }, {foo: 22,bar: 'd'},{foo: 12, bar: 'a'}]}
]
and I would like to get a new array that returns the unique values of all the bar values, so it would look something like:
var uniqueBars = ['a','b','c','d','e'];
I have a solution for this by looping through all of the items, but I'm guessing there is a more efficient way to do this using ES6 features.
Is there a way to create the uniqueBars array above using ES6 features?
You could supply a path of keys and get the values for a Set
.
const
getValues = (data, [key, ...keys]) => data.flatMap(o => keys.length
? getValues(o[key], keys)
: o[key]
),
items = [{ item: [{ foo: 21, bar: 'a' }, { foo: 5, bar: 'e' }, { foo: 167, bar: 'c' }] }, { item: [{ foo: 42, bar: 'a' }, { foo: 45, bar: 'd' }, { foo: 7, bar: 'c' }] }, { item: [{ foo: 99, bar: 'b' }, { foo: 35, bar: 'c' }, { foo: 22, bar: 'e' }] }, { item: [{ foo: 31, bar: 'e' }, { foo: 22, bar: 'd' }, { foo: 12, bar: 'a' }] }],
keys = ['item', 'bar'],
unique = [...new Set(getValues(items, keys))];
console.log(...unique);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments