Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter an object of array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading