1

I'm trying to go through a large object of data, say of the form:

{
 data1: {
     keyA: 'AValue',
     keyB: 'BValue',
     id: 'UniqueID1'
   },
 data2: {
     keyA: 'AValue',
     keyB: 'BValue',
     id: 'UniqueID2'
   },
 data3: {
     keyA: 'AValue',
     keyB: 'BValue',
     id: 'UniqueID1'
   },
 data4: {
     keyA: 'AValue',
     keyB: 'BValue',
     id: 'UniqueID2'
   }
}

Is there a method to go through this object and return to me the unique values for 'id'? E.g I would like to end up with the values

UniqueID1, UniqueID2,

either in an array or an object, it wouldn't matter. Any help on this would be very much appreciated. Thanks.

Sam Matthews
  • 677
  • 1
  • 12
  • 27

3 Answers3

4

You can do this with plain js using map() on Object.keys() and Set to return array of unique keys.

var data = {"data1":{"keyA":"AValue","keyB":"BValue","id":"UniqueID1"},"data2":{"keyA":"AValue","keyB":"BValue","id":"UniqueID2"},"data3":{"keyA":"AValue","keyB":"BValue","id":"UniqueID1"},"data4":{"keyA":"AValue","keyB":"BValue","id":"UniqueID2"}}

var uniq = [...new Set(Object.keys(data).map(e => data[e].id))]
console.log(uniq)

Or with Lodash you can use map and then use uniq.

var data = {"data1":{"keyA":"AValue","keyB":"BValue","id":"UniqueID1"},"data2":{"keyA":"AValue","keyB":"BValue","id":"UniqueID2"},"data3":{"keyA":"AValue","keyB":"BValue","id":"UniqueID1"},"data4":{"keyA":"AValue","keyB":"BValue","id":"UniqueID2"}}

var uniq = _.uniq(_.map(data, 'id'))
console.log(uniq)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
2

You can do this without lodash using Array.reduce and Set

const uniques = Object.keys(data).reduce((acc,key) => acc.add(data[key].id), new Set())
console.log(uniques)
dashton
  • 2,684
  • 1
  • 18
  • 15
1

since you tagged lodash you can do it like this as array:

var myArray = [
 {
     keyA: 'AValue',
     keyB: 'BValue',
     id: 'UniqueID1'
 },
 {
     keyA: 'AValue',
     keyB: 'BValue',
     id: 'UniqueID2'
 },
 {
     keyA: 'AValue',
     keyB: 'BValue',
     id: 'UniqueID1'
 },
 {
     keyA: 'AValue',
     keyB: 'BValue',
     id: 'UniqueID2'
   }
];

_.map(myArray, 'id');

here is the documentation

ShukiB
  • 76
  • 1
  • 7