javascript - underscore.js - create array of unique items from objects embedded in a list of objects -
i've been trying use underscore.js in meteor project i'm working on, can't seem figure out how transform set of objects.
the objects (there's 15k, these two):
[{ "_id": "a_0011223344", "taggedusers": [{ "id": 1122244453, "username": "john123" }], "field": "abc" }, { "_id": "a_0011223345", "taggedusers": [{ "id": 1122244454, "username": "bill123" }, { "id": 1122244455, "username": "jim123" }], "field": "abc" }]
each object can have 1 or more "taggedusers"
objects, , need list of unique "taggedusers.username"
fields. meteor not support mongodb's distinct function, trying use underscore.js instead (per i've read , reccomendation in this post).
in server side console db.mycollection.distinct("taggedusers.username")
returns desired result ["john123", "bill123", "jim123"]
, cannot replicate in underscore.js.
i have been trying combination of _.each
, _.map
, _.pluck
, , _.uniq
, have been unsuccessful. think may have fields being in embedded objects, not sure.
ideally return array of objects looking this:
[{ "id": 1122244453, "username": "john123", "field": "abc" }, { "id": 1122244454, "username": "bill123", "field": "abc" }, { "id": 1122244455, "username": "jim123", "field": "def" }]
taggedusers.username
, taggedusers.id
, , field
feilds, , duplicates removed, happy if array of taggedusers.usernames
in db.colleciton.distinct()
function. ultimately nice know how basic array, array of unique objects, (or maybe how result of db.collection.distinct()
in template helper), or point in right direction appreciated!
based on our conversation, sounds better compute on server via method call. educational purposes, here's how using underscore:
// array of docs somehow var docs = collection.find().fetch(); var taggedusers = _.chain(docs) .map(function(d) { // copy 'field' each of tagged users within doc _.each(d.taggedusers, function(user) { user.field = d.field; }); return d; }) .pluck('taggedusers') // extract tagged users arrays .flatten() // flatten them single array .value(); // taggedusers like: // [ { id: 1122244453, username: 'john123', field: 'abc' }, // { id: 1122244454, username: 'bill123', field: 'abc' }, // { id: 1122244455, username: 'jim123', field: 'abc' }, // { id: 1122244453, username: 'john123', field: 'abc' } ] // compute unique lists of tagged users, docs unique id var utu = _.uniq(taggedusers, false, function(user) {return user.id;});
Comments
Post a Comment