Home > Mobile >  How to display array data that varies in length
How to display array data that varies in length

Time:03-25

I got 2 objects inside the array, and 1st object is longer than the 2nd object. How can i render all of the properties of the 1st object without getting undefined, i get undefined because there are only 2 properties existing in the second object of the array .Also how can i calculate total sum of exercises?

function App() {
  const course = [
    {
      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
        }
      ]
    }
  ]

  // calculate total of exercises
  const totalExercises = course.reduce((total, course) => total   course.exercises, 0);

  return (
    <div className="App">
      <header className="App-header">
        <h1>Seoul</h1>
        <Course course={course} totalExercises={totalExercises} />
      </header>
    </div>
  )
}
function Course({ course, totalExercises }) {
  return (
    <>
      <ul>
        {course.map((course) => (
          <li key={course.id}>
          <p>{course.name} {course.exercises}</p>
          <p>{course.parts[0].name}</p>
          <p>Total exercises: {course.parts[0].exercises},</p>
          <p>{course.parts[1].name}</p>
          <p>Total exercises: {course.parts[1].exercises}</p>
          // Undefined one below
          UNDEFINED <p>{course[0].parts[2].name}</p>
          </li>
        ))}
      </ul>
    </>
  );
}

CodePudding user response:

You could use map the parts array to the elements:

function Course({ course, totalExercises }) {
  return (
    <>
      <ul>
        {course.map((course) => (
          <li key={course.id}>
          <p>{course.name} {course.exercises}</p>
          {
              course.parts.map((part, id)=>(
                  <React.Fragment key={id}
                      <p>{part.name}</p>
                      <p>Total Excercises: {part.exercises}</p>
                  </React.Fragment>
              ))
          }
          </li>
        ))}
      </ul>
    </>
  );
}

CodePudding user response:

If you are not sure that if a key is present in an object and want to render it if it is there without having any error, use ?. to access keys. For example

let a ={name:'Shivansh'};
console.log(a?.name,a?.id);
a ={id:3};
console.log(a?.name,a?.id);

Output for 1st console.log

Shivansh undefined

2nd console.log

undefined 3

One more thing you can give a fallback customized text if you want instead of undefined by using ?? operator.

op1 ?? op2

if op1 gives undefined then op2 is executed

Ex->

console.log(a?.name??'',a?.id??'')
//This will ensure you don't receive undefined but empty string.

To calculate total sum of excercies->

let sum = 0;
course.forEach(course => course ? .parts ? .forEach(part => sum = sum   p 
parseInt(part ? .exercises ? ? 0)))

CodePudding user response:

function Course({ course, totalExercises }) {
    return (
      <>
        <ul>
          {course.map((course) => (
            <li key={course.id}>
            <p>{course.name} {course.exercises}</p>
                {course.parts.map((part,i) => {
                    return(
                        <div key={i}>
                            <p>{part.name}</p>
                            <p>Total exercises: {part.exercises},</p>
                        </div>
                    )
                })}
            </li>
          ))}
        </ul>
      </>
    );
  }

Same way that you are mapping course.map(... you can then map the parts for each course, code above works without an error for me.

  • Related