Mapping an array of objects/Property undefined

Tell us what’s happening:
I want to map an array that contains series of objects. Each object contains a ‘keyTrigger’ property. Values of this property are: ‘Q’, ‘X’ and ‘C’.

I am trying to map this property and to have my React component render it to the screen as buttons (button ‘Q’, ‘X’, etc.)

I receive an error in the console: ‘Uncaught TypeError: Cannot read property ‘keyTrigger’ of undefined’

Why is this property ‘undefined’. What corrections do I need to have this work?

Many thanks.

Your code so far

const beats = [
  {
    keyCode: 81,
    keyTrigger: "Q",
    id: "Heater-1",
    url: "'https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3'"
  },
    
  {
    keyCode: 88,
    keyTrigger: "X",
    id: "Kick",
    url: "https://s3.amazonaws.com/freecodecamp/drums/RP4_KICK_1.mp3"
  },
  {
    keyCode: 67,
    keyTrigger: "C",
    id: "Closed-HH",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Cev_H2.mp3"
  }
];


const key=beats.map((index, item)=>{
  return(
    beats[index].keyTrigger
  );
});


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36

Challenge: Build a Drum Machine

Link to the challenge:

Trying putting console.log(index) before the return statement to see what value index contains. I think this will help you fix your return statment.

Console.log(index) returns first object in a series (image 1)
image

Trying to access this object both with bracket and dot notation, I have rewritten the code in a following way:

const key=beats.map((index)=>{

  console.log(index);
  return(
    beats.index.keyTrigger
  );
});

or:

const key=beats.map((index)=>{

  console.log(index);
  return(
    beats.index[1]
  );
});

or

const key=beats.map((index,item)=>{

  console.log(item);
  return(
    beats.index[item]
  );
});

I am receiving an error message that “keyTrigger” and ‘1’ is undefined, respectively and an error message "cannot read property ‘0’ of undefined in the last case.

In all cases it appears that code correctly reads first object in a row, but treats it as undefined.

Do you have any advice how to proceed further?

Many thanks.

Correct, the variable index holds an object in the array beats. So if you want to access a property in the object that is stored in index how would you do that? Hint: it has nothing to do with the original array beats.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.