Skip to content

Instantly share code, notes, and snippets.

@alexandrricov
Forked from darlanalves/angularjs-filters.js
Last active August 29, 2015 14:18
Show Gist options
  • Select an option

  • Save alexandrricov/c0647a6b3d59d64c79d0 to your computer and use it in GitHub Desktop.

Select an option

Save alexandrricov/c0647a6b3d59d64c79d0 to your computer and use it in GitHub Desktop.
/*
* Exemplo:
* var users = [
* {name: 'Victor Queiroz'},
* {name: 'João Bosco'},
* {nickname: {myNickname: 'Ruan Jordão'}}
* ];
*
* Aplicando o filtro:
* {{ users | pluck:'name | nickname.myNickname' | join:', ' }}
*
* Retorno:
* Victor Queiroz, João Bosco, Ruan Jordão
*
* Dependências:
* - VanillaJS
*/
angular.module('filters', [])
.filter('join', function() {
return function(list, token) {
return (list||[]).join(token);
}
})
.filter('pluck', function() {
function getProperty(obj, prop) {
return prop.split('.')
.reduce(function (m, i) {
return m && typeof m === 'object' ? m[i] : null;
}, obj);
}
function pluck(objects, propertiesString) {
var results = [],
properties,
propsLn;
if (Array.isArray(objects)) {
properties = propertiesString.split('|');
propsLn = properties.length;
if (propsLn > 0) {
objects.forEach(function (obj) {
var property,
val,
i;
for (i = 0; i < propsLn; i++) {
property = properties[i].trim();
val = getProperty(obj, property);
if (val) {
if (Array.isArray(val)) {
results = results.concat(val);
} else {
results.push(val);
}
break;
}
}
});
}
}
return results;
}
return function(objects, property) {
return pluck(objects, property);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment