skip to Main Content
const schoolObj = {
  class10: { studentName: John, result: pass },
  class11: { studentName: Alis, result: pass },
  class12: { studentName: Nick, result: fail },
};

How to create list of studentName if result is pass. class10,11,12 all are dynamic values.I am stuck at how to access this dynamic value in iteration.

I want result like array of student = [John, Alis]

2

Answers


  1. Filter the object values so that you only have the students that have passed left. Then map the student objects so that you get an array with their names.

    const schoolArr = {
      class10: { studentName: 'John', result: 'pass' },
      class11: { studentName: 'Alis', result: 'pass' },
      class12: { studentName: 'Nick', result: 'fail' }
    };
    
    console.log(
      Object.values(schoolArr)
        .filter(({ result }) => result === 'pass')
        .map(({ studentName }) => studentName)
    )
    
    Login or Signup to reply.
  2. const schoolArr = {
      class10: { studentName: 'John', result: 'pass' },
      class11: { studentName: 'Alis', result: 'pass' },
      class12: { studentName: 'Nick', result: 'fail' }
    };
    
    const passStudents = Object.values(schoolArr).reduce((acc, { studentName, result }) => {
      if (result === 'pass') {
        acc.push(studentName);
      }
      return acc;
    }, []);
    
    console.log(passStudents);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search