1

I have this HTML element:

<tags-input
   ng-model="film.genre"
   display-property="name"
   key-property="id"
   placeholder="Genre"
   replace-spaces-with-dashes="false">
  <auto-complete source="loadGenres($query)"></auto-complete>
</tags-input>

This creates a similar tag input field as on Stackoverflow. This is the package being used http://mbenford.github.io/ngTagsInput/

Now loadGenres will return an object like so {name: "Genre name", id: 4}. And it will be stored into film.genre as such. Which is a problem because the API service expects film.genre = [4, ...] basically it must be an array of id's.

I'm not completely sure how to fix this. I tried to make an empty array in my newFilm() method loop the film.genre and add id's from it to that array than assign it to film.genre. However this does not work as when I output the film after doing that I still get an array of Objects where name: id by some logic.

What I get in film.genre:

"genre": [ 0: { "id": 1, "name": "Action" }, 1: { "id": 5, "name": "Comedy" }, ..]  

What I need:

"genre" : [1, 5]
||||||
  • 1
    Can't you just transform the data on the way out? film.genre.map(g => g.id) – Phil May 13 '16 at 4:56
  • can you provide both array what is there and what you want? – Paresh Gami May 13 '16 at 4:58
  • @Phil I tried reassigning the array the way I mentioned in Service so the last place where it goes out to the API service. Same result, I also tried film.genre.map(..) but I get an error saying .map() is undefined. – Sterling Duchess May 13 '16 at 4:58
  • @PareshGami I added what I get and what I need. – Sterling Duchess May 13 '16 at 5:01
  • Well, in your controller it would be $scope.film.genre and by all accounts of the ngTagsInput documentation, it should be an array – Phil May 13 '16 at 5:02
5

March 2019 Update

With ES2015 we can write this more succinctly.

const result = film.genre.map(({id}) => id);

Original Post

var result = film.genre.map(function(genre) {
    return genre.id;
});

Really should be all that you need, see the link below for a working example with your genres.

https://jsbin.com/hoxucikako/edit?js,console,output

||||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.