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

FullStackOpen习题求助:访问嵌套对象数组并统计数据

解决方案

假设你用的是React,下面是完整的组件实现,能渲染每个课程的章节数量、总练习数,以及所有章节的详情:

import React from 'react';

const courses = [
  {
    name: "Half Stack application development",
    id: 1,
    parts: [
      { name: "Fundamentals of React", exercises: 10, id: 1 },
      { name: "Using props to pass data", exercises: 7, id: 2 },
      { name: "State of a component", exercises: 14, id: 3 },
      { name: "Redux", exercises: 11, id: 4 },
    ],
  },
  {
    name: "Node.js",
    id: 2,
    parts: [
      { name: "Routing", exercises: 3, id: 1 },
      { name: "Middlewares", exercises: 7, id: 2 },
    ],
  },
];

const CourseList = () => {
  return (
    <div>
      {courses.map(course => {
        // 计算当前课程的章节数量
        const partCount = course.parts.length;
        // 计算当前课程的总练习数
        const totalExercises = course.parts.reduce((sum, part) => sum + part.exercises, 0);

        return (
          <div key={course.id} className="course">
            <h2>{course.name}</h2>
            <p>章节数量: {partCount} | 总练习数: {totalExercises}</p>
            <ul>
              {course.parts.map(part => (
                <li key={part.id}>
                  {part.name} - 练习数: {part.exercises}
                </li>
              ))}
            </ul>
          </div>
        );
      })}
    </div>
  );
};

export default CourseList;

关键说明:

  • 用courses.map(course => ...)遍历每个课程,确保每个迭代项都是完整的course对象,这样就能直接访问course.parts。
  • 章节数量直接取course.parts.length,数组的length属性就是元素个数。
  • 总练习数用reduce方法累加:初始值设为0,每次迭代把当前part的exercises加到总和里。
  • 所有列表项都要加唯一的key属性,符合React的列表渲染要求。

如果之前你访问parts失败,大概率是遍历课程时没正确拿到course对象,或者数据传递过程中丢失了嵌套结构。检查一下你有没有在父组件到子组件的传值中把course的完整结构传过去——要是把course拆成单个属性传递,肯定拿不到parts。

内容的提问来源于stack exchange,提问作者Conrado Del Carlo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:05:22