获取具有特定属性

时间:2018-02-10 06:38:46

标签: arrays loops typescript object filter

好吧,所以我想创建一个ArtistPage,我需要在页面上放置该艺术家的所有专辑。我在每张专辑中添加了一个名为artistName的属性,作为一种引用它的方式,但如果这是正确的做法则是idk。

这是一个名为 getAlbums 的变量的结果,我在代码中返回一个对象数组,这些对象是“数据库”中的所有相册 - - >

[
 {name: "The Cool", genre: "Hip-Hop", artistName: "Lupe Fiasco", year: "2006", isExplicit: "true", …}
 {name: "Food & Liquor", artistName: "Lupe Fiasco", genre: "Hip-Hop", year: "2006", isExplicit: "true", …}
 {name: "Flume", artistName: "Flume", genre: "Electronic", year: "2012", isExplicit: "true", …}
 {name: "Skin", artistName: "Flume", isExplicit: "true", genre: "Electronic", year: "2016", …}
 {name: "Hybrid Theory", artistName: "Linkin Park", isExplicit: "true", genre: "Nu-Metal", year: "2000", …}
 {name: "Views", artistName: "Drake", genre: "Hip-Hop", year: "2016", isExplicit: "true", …}
 {name: "2014 Forest Hills Drive", artistName: "J.Cole", isExplicit: "true", genre: "Hip-Hop", year: "2014", …}
 {name: "Marshal Matthers LP", artistName: "Eminem", isExplicit: "true", genre: "Hip-Hop", year: "2000", …}
]

我正在使用一个函数来尝试循环所有的属性,但它的错误啊。 它只返回一个专辑

  getAlbumsByArtist(artistName: any) {
    for (var i = 0; i <= this.getAlbums.length - 1; i++) {
      if (this.getAlbums[i].artistName === this.artistName) {
        return this.getAlbums[i];
      }
    }
  }

因此,如果我想在此数组中检索具有属性“artistName:Flume”的所有对象,我将如何进行此操作?

2 个答案:

答案 0 :(得分:1)

您可以使用Array.prototype.filter()

private int medCategoryInt;
private String medCategoryString;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    medCategoryInt = getIntent().getIntExtra("category_int", 0);
    medCategoryString = getIntent().getStringExtra("category_string");
}

您甚至可以定义一个通用方法来搜索任何属性,如下所示:

getAlbumsByArtist (artistName: any) {
  return this.getAlbums.filter(album => album.artistName === artistName);
}

并将其称为getAlbumsByProperty (property: string, value: any) { return this.getAlbums.filter(album => album[property] === value); }

答案 1 :(得分:0)

在这种情况下,您可以使用HigherOrder功能。

var albums=array.filter(album=> {
    if(album.artistName==='Flume') {
    return album;
  }
})
console.log("ans", albums);

工作小提琴:

https://jsfiddle.net/241wkzph/