javascript - 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
解决方案
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.
推荐阅读
- spring - 从 RequestParam 更改为 RequestBody 时“缺少所需的请求正文”
- angular - 在运行时使用 Angular 进行动态路由
- c#-4.0 - C# 通用接口类型返回 Null
- pwa - 注册 Service Worker 失败
- php - 正则表达式将散列括起来的`##WORD=123##`替换为方括号`[object word=123]`
- java - 将字母“a”的第一次出现与字母“o”的最后一次出现交换位置 Java
- sql - 如何在 SSRS 中将照片旋转 90 度 - 通过 SQL 查询导入的图像数据
- angular - Angular 延迟加载模块无法导航到子路由
- javascript - 想要使用 Reactjs 进行更标准的页面导航方式吗?
- asp.net - 禁止创建 .bak 文件