0

The object looks like this: My App.js file looks like this

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: "Redux",
        exercises: 11,
        id: 4,
      },
    ],
  };
return <Course course={course} />;

And I want to total number of exercises filtered into total

const parts = props.Course.parts;

const total = parts.reduce((previousValue, currentValue) => {
    return previousValue + currentValue;
  }, 0);

Output is shown as:

0[object Object][object Object][object Object][object Object]
2
  • 2
    return previousValue + currentValue.excercises should probably do. Commented Sep 5, 2022 at 8:31
  • Remember Course (capital "C") is not the same as course (small "c") for JavaScript. const parts = props.Course.parts; should be const parts = props.course.parts;. Furthermore, as @WiktorZychla already pointed out, you have to access the exercises attribute of the current items. Commented Sep 5, 2022 at 8:35

1 Answer 1

1

As pointed out by @wiktor-zychla, adding exercises in your reduce function will work.

const parts = props.course.parts;

const total = parts.reduce((previousValue, currentValue) => {
    return previousValue + currentValue.excercises;
  }, 0);

Explanation behind your original output,

0[object Object][object Object][object Object][object Object]

The above output is the result of adding object to a number. Hope this helps

Edit: There was also typo in how you are accessing course prop. Fixed it above

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.