You need to enable JavaScript to run this app. JavaScript嵌套map遍历收集艺术家名称为数组的写法
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript嵌套map遍历收集艺术家名称为数组的写法

修正方案

内层map的作用是遍历item.track.artists艺术家对象数组,将每个元素转换为对应的艺术家名称字符串,最终组合为artistNames数组。直接在内层map的回调中返回当前遍历到的艺术家的name属性,即可满足收集名称的需求。

修正后代码

recentTracks.items.map(item => {
  res.push({
    trackName: item.track.name,
    artistNames: item.track.artists.map(artist => {
      console.log(artist.name); // 调试日志可根据需要保留或删除
      return artist.name
    })
  })
})

优化提示

  • 当map的回调仅需返回单值时,可省略函数体大括号和显式return关键字,简化内层遍历逻辑:
artistNames: item.track.artists.map(artist => artist.name)
  • 当前手动初始化空数组res、循环内push的写法存在冗余:外层本身就是map遍历,直接将外层map的返回值赋值给res即可,无需手动操作push:
// 精简后的完整实现
const res = recentTracks.items.map(item => ({
  trackName: item.track.name,
  artistNames: item.track.artists.map(artist => artist.name)
}))

内容的提问来源于stack exchange,提问作者noob9182

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.03 13:36:08