Home > front end >  Returning only a property of an element passed in to a forEach loop in JavaScript
Returning only a property of an element passed in to a forEach loop in JavaScript

Time:09-06

let bloodGroup = bloodCodeArray.forEach(bloodCode => (bloodCode.code.toUpperCase() === bloodType.toUpperCase()) ? bloodCode.code : bloodType);

I expect this to return only a property of 'bloodCode' element (code) in my call back function of an angular code, but this is returning the entire element even though I'm selecting it in the ternary operator. Please explain.

CodePudding user response:

let bloodGroup = bloodCodeArray.map(bloodCode => (bloodCode.code.toUpperCase() === bloodType.toUpperCase()) ? bloodCode.code : bloodType);

CodePudding user response:

let bloodGroup = bloodCodeArray
            .filter(bc => (bc.code.toUpperCase() === bloodType.toUpperCase()) ? bc.code : bloodType)
            .map(bg=>bg.code)
            .pop()

I was able to resolve this by using this code does anyone has a shorter or prettier way of doing the same?

  • Related