You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中提取Spotify API返回对象的title和artist属性?

提取Spotify链接的标题与歌手信息

假设你调用getPreview(url)已经拿到包含title和artist属性的对象,下面两种方法可以把这两个属性提取到单独变量中:

方式1:对象解构赋值(推荐)

这是ES6+最简洁的写法,直接从对象中拆出需要的属性:

// 先获取数据(注意getPreview是异步函数,要加await,且需放在async函数内)
const spotifyInfo = await getPreview("你的Spotify链接");

// 解构提取title和artist
const { title, artist } = spotifyInfo;

// 直接使用变量
console.log(`歌曲名:${title}`);
console.log(`歌手:${artist}`);

方式2:直接属性访问赋值

如果对解构不太熟悉,也可以通过对象属性逐个赋值:

const spotifyInfo = await getPreview("你的Spotify链接");

const title = spotifyInfo.title;
const artist = spotifyInfo.artist;

// 使用变量
console.log(title, artist);

注意事项

  • getPreview是异步函数,必须用await调用,且这段代码要放在async标记的函数里;也可以用.then()链式调用替代:
// 用.then()的写法(适合不熟悉async/await的场景)
getPreview("你的Spotify链接")
  .then(spotifyInfo => {
    const { title, artist } = spotifyInfo;
    console.log(title, artist);
  })
  .catch(error => {
    console.error("获取Spotify信息出错:", error);
  });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 15:05:36