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.
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.
Share Improve this question asked May 21, 2017 at 16:02 Sam MatthewsSam Matthews 6771 gold badge12 silver badges27 bronze badges 03 Answers
Reset to default 4You 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./ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
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)
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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745275351a4620006.html
评论列表(0条)