【问题标题】:Using Javascript Map and Reduce to manipulate Array of Objects使用 Javascript Map 和 Reduce 操作对象数组
【发布时间】:2021-12-02 14:50:03
【问题描述】:

我已经这样做了:

import React from 'react';
const Header =(props)=>{
  const courseRecord =   props.course.map(line => line)
  return(
    <>
      <h2> {courseRecord[0].name }</h2>  
      <h2> {courseRecord[1].name }</h2> 
    </>
  )
}

const Part =(props) =>{
  return(
        <>
         <p>{props.partName}  {props.noOfEx}</p> 
        </>
  )
}

const Content =(props) =>{
  return(
    <div>        
           {props.course
            .map(kourse =>  kourse['parts']
            .map(parti =><Part key={parti['id']} partName = {parti['name']}   noOfEx =  {parti['exercises']}/> )
          )}  
    </div>
  )
}


const Total =(props) =>{
  // const numbers = props.course.parts;
  const numbers = props.course.map(kourse => kourse['parts']);
 
  var exTotal = numbers.reduce((totalExercises,currentValue) =>{
    console.log("totalExercises " , totalExercises , " current value " ,currentValue, " Exercises ",  currentValue[0][1])
      return totalExercises * currentValue.exercises
  },0 );
  return(
        <>
           <p><b>Total of {exTotal} exercises</b></p>
        </>
  )}

  const Course = (props) =>{
    let records =props.course.length;
      return(
        <>
          <h1>Web Development Curriculumn</h1>
          <Header course={props.course}  />
           <Content course ={props.course}/>  
          <Total course ={props.course}/>   
        </>
      )
  }

const  App = () => {
  const course =[
    {
      id: 1,
      name:'Half Stack application development',
      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: 'Destructuring',
          exercises: 14,
          id: 4
        }

      ]
    },
    {
      name :'Node JS',
      id: 2,
      parts:[
        {
          name: 'Routing',
          exercises: 3,
          id: 1
        },
        {
          name: 'middlewares',
          exercises: 7,
          id: 2
        }
      ]
    }
  ]

  return <Course course={course} />
}

export default App;

我希望以这种方式输出格式:

Web Development curriculum

Half Stack Application Development

Fundamentals of React 10
Using props to pass Data 7
State of Component 14
Destructuring 14

Total of 45 exercises

Node Js
Routing 3
Middlewares 7

total of 10 exercises

我明白了:

Web Development Curriculumn

Half Stack application development

Node JS
Fundamentals of React 10

Using props to pass data 7

State of a component 14

Destructuring 14

Routing 3

middlewares 7

Total of NaN exercises

我该如何解决?

【问题讨论】:

    标签: javascript arrays reactjs dictionary reduce


    【解决方案1】:

    当你使用数组时,请使用复数,所以课程数组应该是courses而不是course,只是循环似乎不正确,除了你的代码看起来很好。请检查以下示例代码。

    import React from 'react';
    const Header = ({ course }) => {
      return (
        <>
          <h2> {course.name}</h2>
        </>
      );
    };
    
    const Part = (props) => {
      return (
        <>
          <p>
            {props.partName} {props.noOfEx}
          </p>
        </>
      );
    };
    
    const Content = ({ course }) => {
      return (
        <div>
          {course['parts'].map((parti) => (
            <Part
              key={parti['id']}
              partName={parti['name']}
              noOfEx={parti['exercises']}
            />
          ))}
        </div>
      );
    };
    
    const Total = ({ course }) => {
      // const numbers = props.course.parts;
    
      var exTotal = course['parts'].reduce((totalExercises, currentValue) => {
        console.log(
          'totalExercises ',
          totalExercises,
          ' current value ',
          currentValue,
          ' Exercises ',
          currentValue
        );
        totalExercises = totalExercises + currentValue.exercises;
        return totalExercises;
      }, 0);
      return (
        <>
          <p>
            <b>Total of {exTotal} exercises</b>
          </p>
        </>
      );
    };
    
    const Course = ({ courses }) => {
      return (
        <>
          <h1>Web Development Curriculumn</h1>
          {courses && courses.length
            ? courses.map((course, index) => (
                <div key={index}>
                  <Header course={course} />
                  <Content course={course} />
                  <Total course={course} />
                </div>
              ))
            : null}
        </>
      );
    };
    
    const App = () => {
      const courses = [
        {
          id: 1,
          name: 'Half Stack application development',
          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: 'Destructuring',
              exercises: 14,
              id: 4,
            },
          ],
        },
        {
          name: 'Node JS',
          id: 2,
          parts: [
            {
              name: 'Routing',
              exercises: 3,
              id: 1,
            },
            {
              name: 'middlewares',
              exercises: 7,
              id: 2,
            },
          ],
        },
      ];
    
      return <Course courses={courses} />;
    };
    
    export default App;
    

    Stackblitz

    【讨论】:

    • 谢谢 Naren Murali。已采纳建议。
    • @WanderiMwangi 如果这解决了您的问题,请接受答案。不客气!
    猜你喜欢
    • 2019-02-27
    • 2020-01-29
    • 2012-11-06
    • 2017-02-17
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 2021-03-02
    • 2021-06-20
    相关资源
    最近更新 更多