Home > Software engineering >  Using Javascript Map and Reduce to manipulate Array of Objects
Using Javascript Map and Reduce to manipulate Array of Objects

Time:10-14

I have done this:

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;

I want Output formatted this way :

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

I'm Getting This:

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

How can I work it out?

CodePudding user response:

When you use arrays, please use the plural, so array of courses should be courses not course, just the looping seems to be incorrect, apart from that your code seems fine. Please do check the below example code.

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

  • Related