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

如何获取对象内角色ID?Node.js路由查询角色数据报错排查

问题描述

我有一个书籍数组,每本书籍对象中包含一个角色数组。点击角色时,想展示该角色的姓名、年龄等信息,需要获取每个角色的id。

书籍数据如下:

const PopularBooks = [
  {
    id: 1,
    title: "Harry Potter",
    characters: [
      {
        id: 10,
        name: "Harry Potter",
      },
      {
        id: 11,
        name: "Hermione",
      },
      {
        id: 12,
        name: "Ron",
      },
    ],
  },
  {
    id: 2,
    title: "Lord of the Rings",
    characters: [
      {
        id: 13,
        name: "Frodo",
      },
      {
        id: 14,
        name: "Legolas",
      },
      {
        id: 15,
        name: "Gandalf",
      },
    ],
  },
];

在书籍主页的EJS模板中,将每个角色展示为图片,点击后跳转到带角色id参数的页面:

<% book.characters.forEach(character => { %>
  <div class="portrait">
    <a href="/character/<%= character.id %>">
      <img
        src="/images/characters/book-c-<%= character.id %>.png"
      />
    </a>
    <p><%= character.name %></p>
  </div>
<% }); %>

路由中已设置获取characterId,但遍历数据匹配id时出现错误:Cannot read properties of undefined (reading 'find'),路由代码如下:

const data = require("../data");

router.get("/character/:character", function (req, res, next) {
  const characterId = parseInt(req.params.character);
  const character = data.PopularBooks.characters.find(
    (characters) => characters.id === characterId
  );
  console.log(characterId);
  console.log(character);
  res.render("character", { character });
});

需要获取角色信息搭建专属页面,请问错误原因及修复方法?


错误原因

data.PopularBooks是一个数组,不是单个对象,数组本身没有characters属性,直接访问data.PopularBooks.characters会得到undefined,自然无法调用find方法,所以抛出该错误。

修复方案

需要遍历PopularBooks数组中的每一本书,再在每本书的characters数组里查找目标角色,以下是两种可行实现方式:

方法一:嵌套遍历查找

const data = require("../data");

router.get("/character/:character", function (req, res, next) {
  const characterId = parseInt(req.params.character);
  let character = null;
  
  // 遍历每一本书,逐个查找角色
  for (const book of data.PopularBooks) {
    const foundChar = book.characters.find(char => char.id === characterId);
    if (foundChar) {
      character = foundChar;
      break; // 找到目标后停止遍历,提升效率
    }
  }

  console.log(characterId);
  console.log(character);
  res.render("character", { character });
});

方法二:扁平化角色数组后查找

如果需要频繁查询角色,可以先把所有书籍的角色合并成一个数组,再执行查找:

const data = require("../data");

router.get("/character/:character", function (req, res, next) {
  const characterId = parseInt(req.params.character);
  // 将所有书籍的角色数组扁平化为一个数组
  const allCharacters = data.PopularBooks.flatMap(book => book.characters);
  // 在扁平化数组中查找目标角色
  const character = allCharacters.find(char => char.id === characterId);

  console.log(characterId);
  console.log(character);
  res.render("character", { character });
});

注:如果角色id是全局唯一的,两种方法都适用;若存在id重复的情况,两种方法都会返回第一个匹配到的角色。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 22:36:28