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.

0

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

2 Comments

@NenadVracar you can remove _.values(), and it would still work
@ryeballar Thanks.
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)

Comments

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

1 Comment

yes thanks, and could chain "_.values(data)" to create the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.