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

循环返回[object Object]:多作者书籍表格渲染问题求助

解决表格中Author列显示[object Object]的问题

问题根源是直接在模板字符串中输出对象/数组时,JavaScript会自动调用toString()方法,导致对象被转为[object Object],数组若包含对象也会出现类似问题。以下是两种针对性解决方式:

方案1:友好展示作者姓名(推荐)

根据你描述的「书籍可拥有多个作者,authors是数组,每个Author包含first_name和last_name」,可以遍历authors数组,将每个作者的全名拼接成逗号分隔的字符串,更符合表格的阅读需求:

修改后的完整代码:

function tableCreation(response) {
    let final ="<table>";
    final += "<th>ID</th><th>Title</th><th>Publisher</th><th>Author</th>";
    for (let i = 0; i < response.length; i++) {
        // 处理多作者数组,拼接为易读的姓名列表
        const authorList = response[i].authors.map(author => `${author.first_name} ${author.last_name}`).join(', ');
        final += `<tr><td>${response[i].id}</td><td>${response[i].title}</td><td>${response[i].publisher}</td><td>${authorList}</td></tr>`;
    }
    final +="</table>";
    document.getElementById("field").innerHTML = final;
}

如果实际接口返回的是单个作者对象(字段为author而非authors),则把处理逻辑改为:

const authorName = `${response[i].author.first_name} ${response[i].author.last_name}`;

方案2:用JSON.stringify查看原始结构(仅调试用)

如果只是想临时查看作者对象的完整结构,可以使用JSON.stringify()将对象转为JSON字符串,适合调试场景:

function tableCreation(response) {
    let final ="<table>";
    final += "<th>ID</th><th>Title</th><th>Publisher</th><th>Author</th>";
    for (let i = 0; i < response.length; i++) {
        final += `<tr><td>${response[i].id}</td><td>${response[i].title}</td><td>${response[i].publisher}</td><td>${JSON.stringify(response[i].author)}</td></tr>`;
    }
    final +="</table>";
    document.getElementById("field").innerHTML = final;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:52:46