【问题标题】:Getting objects in an array that has a specific property获取具有特定属性的数组中的对象
【发布时间】:2018-07-20 22:36:58
【问题描述】:

好的,所以我正在尝试制作一个 ArtistPage,我需要将该艺术家的所有专辑放在页面上。我在每张专辑中都放置了一个名为 artistName 的属性,以作为一种引用它的方式,但如果这是正确的做法,我不知道。

这是我在代码中的一个名为 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”的对象,我该怎么做呢?

【问题讨论】:

  • 你好像在用打字稿,对吗?
  • 是的。特别是 Angular 4。

标签: arrays loops typescript object filter


【解决方案1】:

你可以使用Array.prototype.filter():

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

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

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

然后像database.getAlbumsByProperty('artistName', 'Flume')那样称呼它

【讨论】:

  • 我不敢相信我忘记了过滤方法啊啊啊啊。感谢一群人直接回答了我的问题。
【解决方案2】:

在这种情况下,您可以使用 HigherOrder 函数。

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

工作小提琴:

https://jsfiddle.net/241wkzph/

【讨论】:

    猜你喜欢
    • 2020-10-25
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 2013-01-28
    • 2019-05-20
    • 1970-01-01
    相关资源
    最近更新 更多