Skip to content

Instantly share code, notes, and snippets.

@osv
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save osv/258948f7d59ef797fde7 to your computer and use it in GitHub Desktop.
Save osv/258948f7d59ef797fde7 to your computer and use it in GitHub Desktop.
Convert mongo collection to jquery select2 data
/*
Convert mongo collection data to select2 data array that support children (nested)
I use it for convert Meteor collection to select2 data
Example:
data = [ {_id: 1, name: "foo1"},
{_id: 2, name: "child 1 of foo1", p: 1}
{_id: 3, name: "child 2 of foo1", p: 1}
]
console.log( col2sel(data, 'p', 'name', '_id') );
[{text: 'foo1', children: [
{text: 'child 1 of foo1', id: 2}
{text: 'child 2 of foo1', id: 3}
]}]
*/
col2sel = function(array, parentKey, textKey, idKey) {
function find(data, parent) {
return _.chain(data)
// parent filter
.filter(function(item) {
// if parent false then return only empty or itemst that have no parent
if (parent === false &&
(! _.has(item, parentKey) ||
item [parentKey] === ""))
return true;
else
// иначе отдаем те чей отец - parent
return (item[ parentKey ] == parent);
})
// create item for select2 with children if need
.map(function(item) {
var parentId = item [ idKey ],
children = find(array, parentId),
newItem = {
text: item [ textKey ],
};
if (!_.isEmpty(children)) {
newItem.children = children;
} else {
newItem.id = item [ idKey ];
}
return newItem;
})
.value();
}
// start, traverse root items
return find(array, false);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment