1

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

Pierre Roudaut
  • 1,013
  • 1
  • 18
  • 32
  • 2
    [`contacts.map(o => o.id);`](https://jsfiddle.net/tusharj/bfx5qxww/) – Tushar Jun 02 '16 at 12:04
  • show the code instead of `/* my magical parameter */` to clearly understand your question and your effort. – Bhojendra Rauniyar Jun 02 '16 at 12:04
  • The `'filter'` filter will always return the full matching object. You need to create a custom filter. or just use vanilla javascript, like `map` as Tushar is suggesting – Rhumborl Jun 02 '16 at 12:05
  • I didn't now the `'filter'` could only return the full matching object... I think i'll stick with Vanilla JS, looks like a great librairy ;-) – Pierre Roudaut Jun 02 '16 at 12:17
  • I guess this is the similar question: http://stackoverflow.com/questions/15411620/angular-equivalent-of-jquery-map – Roman Koliada Jun 02 '16 at 12:32
  • @Tushar your solution did worked, thanks a lot! If you'd like to give an answer with your suggestion, i'd be happy to accept it. – Pierre Roudaut Jun 02 '16 at 13:00
  • @PierreRoudaut You can see similar answer below, feel free to accept it. – Tushar Jun 02 '16 at 13:02

1 Answers1

0

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]
Coffee-Tea
  • 1,139
  • 9
  • 10