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

在Ember中遍历API返回的嵌套数组并提取category属性问题求助

问题排查与修复方案

现有代码问题

  • map遍历的回调函数没有返回值,你解构categories字段后没有把对应数据抛出,最终model返回的全是undefined组成的数组,无法正常渲染到模板
  • 没有对嵌套的categories数组做适配处理,要提取展示分类属性需要针对嵌套结构做遍历逻辑适配

修复后的代码

import Route from '@ember/routing/route';
export default class BooksRoute extends Route {
  async model(){
    let response = await fetch('https://json-api-smaiil.herokuapp.com/books');
    let parsed = await response.json();
    console.log(parsed);
    // 方案1:保留书籍和分类的对应关系,返回每个书籍关联的分类数组
    return parsed.map((book) => {
      return {
        id: book.id,
        bookName: book.name,
        categories: book.categories
      }
    });
    // 如果需要把所有书籍的分类合并为一维数组直接展示,替换上面的return为以下代码
    // return parsed.flatMap(book => book.categories);
  }
}

模板渲染示例

如果使用上面的方案1返回结构,在app/templates/books.hbs中可以按以下方式遍历展示分类:

{{#each @model as |book|}}
  <div class="book-item">
    <h4>书籍名称:{{book.bookName}}</h4>
    <p>所属分类:</p>
    <ul>
      {{#each book.categories as |category|}}
        <li>{{category.name}}</li>
      {{/each}}
    </ul>
  </div>
{{/each}}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 09:27:03