首页 > 解决方案 > I cant look for a value in a object array, it returns me error

问题描述

Hello everyone I'm doing this music player and this is the song loader but the problem is that when I try to assing the value to song constant with lookSongbyId function it returns me an error idk why

let queue = [
    {
        id: 1,
        name: 'Crush',
        artist: 'Glades',
    }
]

const loadSong = (id) =>{


    function lookSongbyId(id)
    {
        queue.forEach(currentSong => {
            if(currentSong.id == id )
            {
                return currentSong
            }   
        })
    }

    const song = lookSongbyId(id)


    console.log(`la canción ${song.name} ha sido cargada`)
}
loadSong(1)

song constant is undefined, and I dont know why aghhh If u could help me with this code I've been so thankful with u :DDD

标签: javascriptarraysforeachscope

解决方案


you can use directly filter if you want to return more than item or find if you want only want (if the id is unique)

const queue = [
      {
        id: 1,
        name: 'Crush',
        artist: 'Glades',
      },
      {
        id: 2,
        name: 'Another Song2',
        artist: 'Favio Figueroa',
      }
    ];
    const useFilter = queue.filter((row) => row.id === 1 );
    console.log('useFilter', useFilter) // [ { id: 1, name: 'Crush', artist: 'Glades' } ]
    const useFind = queue.find((row) => row.id === 2 );
    console.log('useFind', useFind) // { id: 2, name: 'Another Song2', artist: 'Favio Figueroa' }

you can add in your function that logic.


推荐阅读