Sterling Duchess
Sterling Duchess

Reputation: 2080

Save array of id's instead of objects

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]

Upvotes: 1

Views: 1636

Answers (1)

sheeldotme
sheeldotme

Reputation: 2503

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

Upvotes: 5

Related Questions