保存id的数组而不是对象

时间:2022-06-12 17:07:03

I have this HTML element:

我有这个HTML元素:

<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 *. This is the package being used http://mbenford.github.io/ngTagsInput/

这将创建与*上类似的标记输入字段。这是使用的包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.

现在loadGenres将返回一个像{name:“Genre name”,id:4}这样的对象。它将被存储到film.genre中。这是一个问题,因为API服务期望film.genre = [4,...]基本上它必须是一个id的数组。

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.

我不完全确定如何解决这个问题。我试图在newFilm()方法中创建一个空数组,然后循环播放film.genre并将id从其中添加到该数组,而不是将其分配给film.genre。然而,这不起作用,因为当我输出电影后,我仍然得到一个对象数组名称:id由一些逻辑。

What I get in film.genre:

我在film.genre得到了什么:

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

What I need:

我需要的:

"genre" : [1, 5]

1 个解决方案

#1


4  

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

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

#1


4  

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

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