简体   繁体   English

使用.filter 在数组中搜索数组

[英]Using .filter to search through an array within an array

I would like to understand how to use the.filter method to search through an array within an array.我想了解如何使用 .filter 方法在数组中搜索数组。 I am creating a collection array that is filled with album objects.我正在创建一个充满专辑对象的集合数组。 Within the album objects are a property named tracks which itself is an array filled with track objects.在专辑对象中有一个名为tracks 的属性,它本身是一个填充了track 对象的数组。

function addToCollection(title, artist, yearPublished, tracks) {
  const album = {
    title: title,
    artist: artist,
    yearPublished: yearPublished,
    tracks: tracks,
  }
  collection.push(album);
  return album;
} // end addToCollection

function addTrack(trackNumber, name, duration) {
    const track = {
        trackNumber: trackNumber,
        name: name,
        duration: duration
    }
    return track;
}

I am writing a search function to return certain albums if they meet the search criteria.我正在编写搜索 function 以返回满足搜索条件的某些专辑。 The following line of code will return an array that contains the album objects that match the.artist property from the parameter that was passed in.以下代码行将返回一个数组,其中包含与传入参数中的 .artist 属性匹配的专辑对象。

function search(query) {
    const foundArtist = collection.filter( x => x.artist === query.artist );

My question is how to do use the.filter method to sort through the array of tracks within each album to find an individual track name or track duration.我的问题是如何使用 .filter 方法对每个专辑中的曲目数组进行排序,以找到单独的曲目名称或曲目持续时间。

This following code does not find the track name even though query.trackName exists.即使 query.trackName 存在,以下代码也找不到轨道名称。

const foundTrackName = collection.filter( x => x.tracks.name === query.trackName);

Whereas when I specify the specific track it does return the entire album.而当我指定特定曲目时,它会返回整个专辑。

const foundTrackName = collection.filter( x => x.tracks[4].name === query.trackName);

You need to iterate tracks as well.您还需要迭代tracks

const foundTrackName = collection.filter(({ tracks }) =>
    tracks.some(({ name }) =>
        name === query.trackName
    )
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM