0

I'm coding a drumkit for FreeCodeCamp's front end certificate.

I'm having problems thinking of a way to find if the event.keyCode object is in the keyCode property of one of my objects in the array.

export default class Drumkit extends Component {
   state = {
      keys: [{
        key: 'Q', 
        keyCode: 81,
        src: ''
      }, {
        key: 'W', 
        keyCode: 87,
        src: ''
      },
      ...
     ]
  }

  handleKeyPress(event) {
    //if event.keyCode === keyCode property in object array
       const keyDiv = document.getElementById(event.keyCode)
       keyDiv.play();
  }
Sushanth --
  • 55,259
  • 9
  • 66
  • 105

2 Answers2

0

You can use the find method available on the array prototype.

const foundKey = this.state.keys.find(key => event.keyCode === key.keyCode);

if(!!foundKey) {
   const keyDiv = document.getElementById(event.keyCode);

   keyDiv.play();
}
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
0
for(let i = 0; i < this.state.keys.length; i++){
    if (this.state.keys[i].keyCode === event.keyCode){
        \\ do something if true
    }
}

You could also do a simple for loop and find it easily too.

AttemptedMastery
  • 738
  • 6
  • 21