-1
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]

pilchard
  • 12,414
  • 5
  • 11
  • 23
CBP
  • 33
  • 6
  • see: [Object.values()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values) – pilchard May 01 '23 at 15:21
  • `Object.values(schoolObj).filter(e => e.result ==='pass')` – cmgchess May 01 '23 at 15:22
  • 2
    Does this answer your question? [Filter object properties by key in ES6](https://stackoverflow.com/questions/38750705/filter-object-properties-by-key-in-es6) – pilchard May 01 '23 at 15:22
  • or and [Filter object of objects](https://stackoverflow.com/questions/62933394/filter-object-of-objects) and [From an array of objects, extract value of a property as array](https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array) – pilchard May 01 '23 at 15:24
  • 1
    @CBP changing the input values after answers have already been posted is discouraged and invalidates already accurate and upvoted answers. – pilchard May 01 '23 at 15:37
  • Adjusting the existing answers to fit your ["new" structure](https://stackoverflow.com/revisions/76148066/5) isn't too hard either. For example `({ result }) => result === 'pass'` becomes `({ exam }) => exam.result === 'pass'`, a similar thing happens with the `studentName`. – 3limin4t0r May 01 '23 at 15:42

2 Answers2

2

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)
)
Thomas Frank
  • 1,404
  • 4
  • 10
1

Here is another approach to your solution.

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);
Ivan Chew
  • 9
  • 4
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 02 '23 at 20:39