简体   繁体   中英

Trying to return an object of an array returning undefined using the find() function

I'm trying to return an album object given a specified track. Given this array:

const albumCollection = [
    {
        id: 2125,
        title: 'Use Your Illusion',
        artist: "Guns N' Roses",
        tracks: ['November Rain', "Don't Cry"]
    },

    {
        id: 2975,
        title: '1999',
        artist: 'Prince',
        tracks: ['1999', 'Little Red Corvette']
    },

    {
        id: 1257,
        title: 'Transformer',
        artist: 'Lou Reed',
        tracks: ['Vicious', 'Perfect Day', 'Walking on the Wild Side']
    },

And using the following function, both the commented and uncommented code returns undefined. I'm trying to understand why. What I'm trying to do is return the album as an object based on the track name.

function getAlbumWithTrack(track) {
    /*
    const result = albumCollection.find((item) => item.id === track);
    console.log(result);
    */
    return albumCollection.find(function (title) {
        return title.track === track;
    });
}

console.log(getAlbumWithTrack('Little Red Corvette'));
console.log(getAlbumWithTrack('November Rain'));
console.log(getAlbumWithTrack('perfect day'));

On this line:

return title.track === track;

There is no property called track on your objects. It's called tracks , and it's an array so it would never equal a string value. I suspect you're looking for this:

return title.tracks.includes(track);

For example:

 const albumCollection = [ { id: 2125, title: 'Use Your Illusion', artist: "Guns N' Roses", tracks: ['November Rain', "Don't Cry"] }, { id: 2975, title: '1999', artist: 'Prince', tracks: ['1999', 'Little Red Corvette'] }, { id: 1257, title: 'Transformer', artist: 'Lou Reed', tracks: ['Vicious', 'Perfect Day', 'Walking on the Wild Side'] } ]; function getAlbumWithTrack(track) { return albumCollection.find(function (title) { return title.tracks.includes(track); }); } console.log(getAlbumWithTrack('Little Red Corvette')); console.log(getAlbumWithTrack('November Rain')); console.log(getAlbumWithTrack('perfect day'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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