Pierre Roudaut Pierre Roudaut - 6 months ago 11
AngularJS Question

Angular $filter select property only

is there a built in way to use angular's $filter service to retrieve an array of containing only a specific property from an array of objects ?

var contacts = [
{
name: 'John',
id: 42
},
{
name: 'Mary',
id: 43
},
];

var ids = $filter('filter')(contacts, /* my magical parameter */);
console.log(ids); //output [42, 43]


Any help or link to a related topic would be much appreciated, thanks

Answer

You don't need use $filter service of angularjs, you can use .map() method (core JS, I mean ES5):

var contacts = [
    {
      name: 'John',
      id: 42
    },
    {
      name: 'Mary',
      id: 43
    },
];

var ids = contacts.map(function(contact) {
   return contact.id;
});

console.log(ids); //output [42, 43]